ConditionalPanel with more than one condition are true - r

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})

Related

Selection problem of bucketlist in sortable package

There are 3 districts which are A, B, and C in my data. I would like to establish a new district from the subdistricts of the current districts. For example, I select 2 of 3 districts via selectInput. And then, I would like to use bucket_list for selecting the subdistricts. The bucket list should show the subdistricts of selected districts. I do not want to see subdistricts of 3rd districts on a bucket list. I want to see only what I selected via selectInput. I could not manage this. After that, I want to create some tables using the DT package based on what I selected in the bucket list. My codes are below. I would be happy if you could help.
Here’s code:
library(shiny)
library(semantic.dashboard)
library(ggplot2)
library(plotly)
library(DT)
library(sortable)
library(gsheet)
data <- gsheet2tbl('https://docs.google.com/spreadsheets/d/1TqFoIQzTYyWKP8N43jcAxAV71TTA7ldfeRcGtpqfarM/edit#gid=201611728')
ui <- dashboardPage(
dashboardHeader(color = "green",title = "NEW DISTRICT", inverted = TRUE, size = "very wide"),
dashboardSidebar(
size = "thin", color = "teal",
sidebarMenu(
menuItem(tabName = "dist", "NEW DISTRICT ESTABLISHMENT", icon = icon("tree")),
menuItem(tabName = "subdist", "NEW SUBDISTRICT ESTABLISHMENT", icon = icon("tree"))
)
),
dashboardBody(
tabItems(
selected = 1,
tabItem(
tabName = "dist",
fluidRow(
fluidPage( textInput("caption", "ENTER THE NAME OF THE NEW DISTRICT", "", width = 500, placeholder = "PLEASE ENTER NEW NAME HERE!"),
fluidRow(column(5, verbatimTextOutput("value1"))),
hr(),
fluidPage(
selectInput("select", label = h3("PLEASE SELECT THE DISTRICTS!"),
choices = (data$DISTRICT),
selected = 0,
multiple= TRUE),
hr(),
fluidRow(column(3, verbatimTextOutput("value")))
),
),
if(interactive()) {
bucket_list(
header = c("NEW DISTRICT ESTABLISHMENT"),
add_rank_list(
text = "PLEASE SELECT SUBDISTRICT HERE!",
labels = "x",
options = sortable_options(
multiDrag = TRUE),
),
add_rank_list(
text = "select the subdistricts of the new district"
),
add_rank_list(
text = "select the subdistrict of the current district"
),
add_rank_list(
text = "select the subdistrict of the current district 2"
)
)
}
),
)
)
),
theme = "cerulean"
)
server <- shinyServer(function(input, output, session) {
observe({ print(input$select)
#output$x <- data$SUBDISTRICT[data$DISTRICT == input$select]
#output$x <- data %>% filter(DISTRICT == input$select) %>% select(SUBDISTRICT)
#updateSelectInput(session,"SUBDISTRICT","Select a SUBDISTRICT Category",choices = unique(x))
})
output$value <- renderText({paste(input$select)
})
output$value1 <- renderText({ input$caption })
})
shinyApp(ui, server)
Also, when I remove # on these codes:
observe({ print(input$select)
#output$x <- data$SUBDISTRICT[data$DISTRICT == input$select]
#output$x <- data %>% filter(DISTRICT == input$select) %>% select(SUBDISTRICT)
#updateSelectInput(session,"SUBDISTRICT","Select a SUBDISTRICT Category",choices = unique(x))
The shiny close itself.
Perhaps this will meet your needs
library(shiny)
library(semantic.dashboard)
library(ggplot2)
library(plotly)
library(DT)
library(sortable)
library(gsheet)
data <- gsheet2tbl('https://docs.google.com/spreadsheets/d/1TqFoIQzTYyWKP8N43jcAxAV71TTA7ldfeRcGtpqfarM/edit#gid=201611728')
ui <- dashboardPage(
dashboardHeader(color = "green",title = "NEW DISTRICT", inverted = TRUE, size = "very wide"),
dashboardSidebar(
size = "thin", color = "teal",
sidebarMenu(
menuItem(tabName = "dist", "NEW DISTRICT ESTABLISHMENT", icon = icon("tree")),
menuItem(tabName = "subdist", "NEW SUBDISTRICT ESTABLISHMENT", icon = icon("tree"))
)
),
dashboardBody(
tabItems(
selected = 1,
tabItem(
tabName = "dist",
fluidRow(
fluidPage( textInput("caption", "ENTER THE NAME OF THE NEW DISTRICT", "", width = 500, placeholder = "PLEASE ENTER NEW NAME HERE!"),
fluidRow(column(5, verbatimTextOutput("value1"))),
hr(),
fluidPage(
selectInput("select", label = h3("PLEASE SELECT THE DISTRICTS!"),
choices = unique(data$DISTRICT),
selected = 0,
multiple= TRUE),
hr(),
fluidRow(column(3, verbatimTextOutput("value"))),
DTOutput("t1"),
selectInput("subdistrict", label = h3("PLEASE SELECT THE SUBDISTRICTS!"),
choices = unique(data$SUBDISTRICT),
selected = 0,
multiple= TRUE)
)
),
uiOutput("mybucket")
),
)
)
),
theme = "cerulean"
)
server <- shinyServer(function(input, output, session) {
dat <- reactive({
data[data$DISTRICT %in% req(input$select),]
})
output$mybucket <- renderUI({
req(dat())
bucket_list(
header = c("NEW DISTRICT ESTABLISHMENT"),
add_rank_list(
text = "PLEASE SELECT SUBDISTRICT HERE!",
labels = unique(dat()$SUBDISTRICT),
options = sortable_options(
multiDrag = TRUE),
),
add_rank_list(
text = "select the subdistricts of the new district"
),
add_rank_list(
text = "select the subdistrict of the current district"
),
add_rank_list(
text = "select the subdistrict of the current district 2"
)
)
})
output$t1 <- renderDT(dat())
observeEvent(input$select, {
updateSelectInput(session,"subdistrict","Select a SUBDISTRICT Category",choices = unique(dat()$SUBDISTRICT))
})
output$value <- renderText({paste(input$select)})
output$value1 <- renderText({ input$caption })
})
shinyApp(ui, server)

Reactivity and Renders doesn't work when switching to another tabPanel

I have a reproducible example below where only the first tabPanel is working, however when I switch to another panel, I don't get any renders (the toggle becomes un-interactable also). I have looked into conditionalPanel however I see them getting done without the use of mainPanel I was wondering if it possible to have tabs where each tab has its own mainPanel , so I can see a different sidebar and an output contained within different tabs. Any help is welcome!
options(scipen = 99999) #converts the sci numbers to their regular format
library(shiny)
library(shinyjs)
library(shinyWidgets)
library(shinyalert)
library(esquisse)
library(DT)
library(dplyr)
#library(devtools)
#library(remotes)
#remotes::install_github("dreamRs/esquisse")
library(hrbrthemes)
library(ggthemes)
library(ggplot2)
library(svglite)
ui <- fluidPage(
shinyjs::useShinyjs(), # enables javascript/jQuery enhanchments
# Create Right Side Text
navbarPage(
title= div(HTML("G<em>T</em>")),
#General reports
tabPanel("General Reports",
shinyWidgets::materialSwitch(inputId = "toggleSidebar", label = "Toggle Panel: ",
value = TRUE, status = "warning"),
sidebarLayout(
# radio/action buttons
sidebarPanel(
id = "Sidebar",
shinyWidgets::prettyRadioButtons(
inputId = "controller",
label = "Choose:",
choices = c("About"= 1,
"iris"= 2),
icon= icon("check"),
selected = 1,
status = "success",
animation="smooth"
),
br(),
br(),
a(actionButton(inputId = "admin_email", label = "Contact",
icon = icon("envelope", lib = "font-awesome")),
href="mailto:xyz#email.us")
),
#panel where output is shown from server
mainPanel(
id = "main_panel",
tabsetPanel(
id = "hidden_tabs",
type = "hidden",
tabPanelBody(
"panel1", "Text coming soon."
),
tabPanelBody(
"panel2",
tabsetPanel(
tabPanel("Data", DT::DTOutput('panel2_data')),
tabPanel(
"DIY Plot",
esquisse::esquisse_ui(
id = "esquisse2",
header = FALSE,
container = esquisseContainer(
width = "100%", height = "760px", fixed = FALSE
),
controls = c("labs", "parameters", "appearance", "filters", "code")
)
)
)
)
)
)
)
),
# monthly reports
tabPanel("Extra General Reports",
shinyWidgets::materialSwitch(inputId = "toggleSidebar", label = "Toggle Panel: ",
value = TRUE, status = "warning"),
sidebarLayout(
# radio/action buttons
sidebarPanel(
id = "Sidebar",
shinyWidgets::prettyRadioButtons(
inputId = "controller",
label = "Choose:",
choices = c("About"= 3,
"mtcars"= 4),
icon= icon("check"),
selected = 3,
status = "success",
animation="smooth"
),
br(),
br(),
a(actionButton(inputId = "admin_email", label = "Contact",
icon = icon("envelope", lib = "font-awesome")),
href="mailto:xyz#email.us")
),
#panel where output is shown from server
mainPanel(
id = "main_panel",
tabsetPanel(
id = "hidden_tabs",
type = "hidden",
tabPanelBody(
"panel3", "Text coming soon."
),
tabPanelBody(
"panel4",
tabsetPanel(
tabPanel("Data", DT::DTOutput('panel4_data')),
tabPanel(
"DIY Plot",
esquisse::esquisse_ui(
id = "esquisse4",
header = FALSE,
container = esquisseContainer(
width = "100%", height = "760px", fixed = FALSE
),
controls = c("labs", "parameters", "appearance", "filters", "code")
)
)
)
)
)
)
)
),
#resizes the navbar tabs/button
tags$head(tags$style(HTML('.navbar-brand {width: 270px; font-size:35px; text-align:left;
font-family: "serif";')))
)
)
server <- function(input, output, session) {
# this event hides the side panel when toggled on/off
observeEvent(input$toggleSidebar, {
shinyjs::toggle(id = "Sidebar", condition = input$toggleSidebar)
if(!isTRUE(input$toggleSidebar)) {
shinyjs::runjs("$('#main_panel').removeClass('col-sm-8').addClass('col-sm-12')")
} else {
shinyjs::runjs("$('#main_panel').removeClass('col-sm-12').addClass('col-sm-8')")
}
})
# here we put all the data
data_sets <- list(df1 = data.frame(),
df2 = iris,
df3 = data.frame(),
df4 = mtcars)
# store current dataset in reactive so we can work with plot panels
data_to_use <- reactiveValues(name = "df", data = data.frame())
# modules only need to be called it once but individually for esquisse
esquisse::esquisse_server(id = "esquisse2", data_rv = data_to_use)
esquisse::esquisse_server(id = "esquisse4", data_rv = data_to_use)
observeEvent(input$controller, {
# skip first panel since it is used to display navigation
updateTabsetPanel(session, inputId= "hidden_tabs", selected = paste0("panel", input$controller))
# enswure value is avilable throught selected tabSet
req(input$controller)
# get current data and df name
data_to_use$data <- data_sets[[as.numeric(input$controller)]]
data_to_use$name <- names(data_sets[as.numeric(input$controller)])
# update table and sum. Use server = FALSE to get full table
output[[paste0('panel', input$controller, '_data')]] <- DT::renderDT(server = FALSE, {
DT::datatable(data_to_use$data,
filter = 'top',
extensions = 'Buttons')})
})
}
#runs the app
shinyApp(ui= ui, server= server)
You have two radioButtons, one for each sidebar, but both of them have the inputId = "controller". Same with inputId = "toggleSidebar". InputIds need to be unique in shiny!
I suggest you either use a single sidebar for the entire app, or since both tabs are essentially identical you can also use modules.

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()?

Populate selectizeInput on first load

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)

Reset tableoutput with action button in shinydashboard

I have an shinydashboard app, the app get an filter box and a tabset which show a datatatable depending on filter.
I have a reset button which reset the filters whith shinyjs::reset function, and I want to reset also the tableset and showing the complete table or nothing.
I want also to do it for a valuboxes.
My app is like this :
For server interface I have an basic : output$tableprint_A <- DT::renderDataRable ({})
ui :
body <- dashboardBody(
tabItems(
#### First tab item #####
tabItem(tabName = "fpc",
fluidRow(
infoBoxOutput("kpm_inf", width = 6),
infoBoxOutput(outputId = "fpc_inf", width = 6)
),
fluidRow(
box(title = "Variables filter",
shinyjs::useShinyjs(),
id = "side_panel",
br(),
background = "light-blue",
solidHeader = TRUE,
width = 2,
selectInput("aaa", "aaa", multiple = T, choices = c("All", as.character(unique(fpc$aaa))))
br(),
br(),
p(class = "text-center", div(style = "display:inline-block", actionButton("go_button", "Search",
icon = icon("arrow-circle-o-right"))),
div(style = "display:inline-block", actionButton("reset_button", "Reset",
icon = icon("repeat")))),
p(class = 'text-center', downloadButton('dl_fpc', 'Download Data'))),
tabBox(
title = tagList(),
id = "tabset1",
width = 10,
tabPanel(
"A \u2030 ",
DT::dataTableOutput("tableprint_A"),
bsModal(id = 'startupModal', title = 'Update message', trigger = '',
size = 'large',
tags$p(tags$h2("Last update of A : 01/09/2017",
br(), br(),
"Last update of B : 01/09/2017",
br(), br(),
"Last update of C : 01/09/2017",
style = "color:green", align = "center")))
),
tabPanel(
"B % Table",
DT::dataTableOutput("tableprint_B")),
type = "pills"
)
),
fluidRow(
# Dynamic valueBoxes
valueBoxOutput("info_gen", width = 6)
)
I tried this :
observeEvent(input$reset_button, {
output$tableprint_A <- NULL
})
Edit:
I want something like that, but when I action the search button I want it to appear again :
shinyjs::onclick("reset_button",
shinyjs::toggle(id = "tableprint_A", anim = TRUE))
You should try this out:
output$tableprint_A <- renderDataTable({
if(input$reset_button == 1) {
NULL
}else{
datatable(...)
}
})
if the button is clicked then nothing will be displayed, else the datatable is shown.
[EDIT]
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(selectInput("select", "select", choices = unique(iris$Species), multiple = T),
actionButton("go_button", "Search",
icon = icon("arrow-circle-o-right")),
actionButton("reset_button", "Reset",
icon = icon("repeat")),
DT::dataTableOutput('tbl')),
server = function(input, output) {
values <- reactiveValues(matrix = NULL)
observe({
if (input$go_button == 0)
return()
values$matrix <- iris[iris$Species %in% input$select, ]
})
observe({
if (input$reset_button == 0)
return()
values$matrix <- NULL
})
output$tbl = DT::renderDataTable({
datatable(values$matrix, options = list(lengthChange = FALSE))}
)
}
)

Resources