How do I make persistent checkboxes with DT::datatable in Shiny?
Asked Answered
H

1

1

Using this answer, I made a DT::datatable in Shiny which contain a column of checkboxes, but I'm having an issue where if I check some boxes, go to another page on the table, then return to the original page, the boxes are now unchecked. How can I make the box-checking persistent when switching pages? Here's a minimal example:

library(shiny)
library(DT)
runApp(
  list(ui = fluidPage(
    dataTableOutput("dtout")),
    server = function(input, output, session) {
      
      shinyInput <- function(FUN, id, num, ...) {
        inputs <- character(num)
        for (i in seq_len(num)) {
          inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
        }
        inputs
      }
      
      output$dtout <- renderDataTable({
        datatable(
          cbind(Pick = shinyInput(checkboxInput, "srows_", nrow(mtcars), value = NULL, width = 1), mtcars),
          options = list(drawCallback= JS('function(settings) {Shiny.bindAll(this.api().table().node());}')),
          selection = 'none', escape = F)
      })
    })
)
Holsworth answered 15/7, 2023 at 16:41 Comment(1)
In case this helps, {reactable} has a similar feature inbuilt for selecting rows. glin.github.io/reactable/articles/examples.html#select-on-clickIntraatomic
S
1

In order to keep the checkbox state while moving between pages, you have to disable server side processing. You can set this by calling DT::renderDataTable with server = FALSE.

enter image description here

Complete minimal example:

library(shiny)
library(DT)
runApp(list(
    ui = fluidPage(dataTableOutput("dtout")),
    server = function(input, output, session) {
        shinyInput <- function(FUN, id, num, ...) {
            inputs <- character(num)
            for (i in seq_len(num)) {
                inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
            }
            inputs
        }
        
        output$dtout <- renderDataTable({
            datatable(
                cbind(
                    Pick = shinyInput(
                        checkboxInput,
                        "srows_",
                        nrow(mtcars),
                        value = NULL,
                        width = 1
                    ),
                    mtcars
                ),
                options = list(
                    drawCallback = JS(
                        'function(settings) {Shiny.bindAll(this.api().table().node());}'
                    )
                ),
                selection = 'none',
                escape = F
            )
        }, server = FALSE)
    }
))
Suspensive answered 23/7, 2023 at 11:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.