How to make shinyWidget materialSwitch update checkboxGroupButtons

43 views Asked by At

I want to use a shinyWidgets materialSwitch to select all / deselect all when switched, in an adjacent set of checkboxGroupButtons. But in my code below, the switch has no effect on the check boxes:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  checkboxGroupButtons(
    inputId = "somevalue",
    choices = c("A", "B", "C"),
    label = "My label"
  ),
  
  verbatimTextOutput(outputId = "res"),
  
  materialSwitch(
    inputId = "clear",
    label = "Select all?",
    value = TRUE, 
    status = "info"
  )

)

server <- function(input, output, session) {
  
  output$res <- renderPrint({
    input$somevalue
  })
  
  observeEvent(input$clear, {

    if (input$clear) {
      updateCheckboxGroupInput(session, "somevalue", selected = c("A", "B", "C"))
    } else {
      updateCheckboxGroupInput(session = session, inputId = "somevalue", selected = character(0))
    }

  })  

}

shinyApp(ui = ui, server = server)

I think the problem is in the if statement as if I skip that I can get the check box group to update, either selecting all or deselecting all every time it's hit. I've also tried using observe instead of observeEvent as suggested here but to no effect.

Can anyone put me right?

1

There are 1 answers

0
YBS On

With checkboxGroupButtons you should use updateCheckboxGroupButtons, and with checkboxGroupInput you can use updateCheckboxGroupInput. Both of them work. Try this

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  checkboxGroupButtons(
  # checkboxGroupInput(
    inputId = "somevalue",
    choices = c("A", "B", "C"), selected = c("A", "B"),
    label = "My label"
  ),
  
  verbatimTextOutput(outputId = "res"),
  
  materialSwitch(
    inputId = "clear",
    label = "Select all?",
    value = TRUE, 
    status = "info"
  )
  
)

server <- function(input, output, session) {
  
  output$res <- renderPrint({
    input$somevalue
  })
  
  selection <- eventReactive(input$clear, {
    selected = character(0)
    if (input$clear) {
      selected = c("A", "B", "C")
    } 
    selected
  })
  
  observeEvent(selection(), {
    updateCheckboxGroupButtons(session, 
    # updateCheckboxGroupInput(session, 
                             inputId = "somevalue",
                             choices = c("A", "B", "C"),
                             selected = selection())
  },ignoreNULL = FALSE, ignoreInit = TRUE)  
  
}

shinyApp(ui = ui, server = server)