To make the checkbox state persistent when switching pages in an R Shiny DataTable, you can use server-side processing and handle the checkbox input separately from the DataTable itself. Here's an updated version of your code that demonstrates this:
library(shiny)
library(DT)
runApp(
list(ui = fluidPage(
dataTableOutput("dtout")),
server = function(input, output, session) {
shinyInput <- function(FUN, id, num, values = NULL, ...) {
inputs <- character(num)
for (i in seq_len(num)) {
inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, value = values[i], ...))
}
inputs
}
# Store checkbox values in a reactiveValues object
checkboxValues <- reactiveValues(values = rep(FALSE, nrow(mtcars)))
observe({
# Update checkbox values when checkboxes are changed
for (i in seq_along(checkboxValues$values)) {
checkboxId <- paste0("srows_", i)
checkboxValues$values[i] <- input[[checkboxId]]
}
})
output$dtout <- renderDataTable({
# Add a column for checkboxes dynamically based on checkboxValues$values
datatable(
cbind(Pick = shinyInput(checkboxInput, "srows_", nrow(mtcars), values = checkboxValues$values, width = 1), mtcars),
options = list(
drawCallback = JS('function(settings) {Shiny.unbindAll(this.api().table().node()); Shiny.bindAll(this.api().table().node());}'),
serverSide = TRUE # Enable server-side processing
),
selection = 'none', escape = FALSE
)
}, server = TRUE) # Set server = TRUE to enable server-side processing
# Update checkbox values when the table is re-rendered
observeEvent(input$dtout_state_change$page, {
selectedRows <- input$dtout_rows_selected
if (!is.null(selectedRows)) {
for (i in seq_along(checkboxValues$values)) {
checkboxValues$values[i] <- i %in% selectedRows
}
}
})
})
)
In this modified code:
We store the checkbox values in a reactiveValues
object called checkboxValues
. This allows us to keep track of the state of each checkbox.
We use an observer to update the checkboxValues
when any checkbox is changed. This ensures that the values are always up to date.
In the renderDataTable
function, we dynamically generate the checkboxes using the shinyInput
function. We pass in the values
argument to initialize the checkboxes with the stored values from checkboxValues
.
We enable server-side processing by setting serverSide = TRUE
in the datatable
options. This allows the DataTable to handle pagination and other operations efficiently.
We use an observer to update the checkboxValues
whenever the table is re-rendered. This ensures that the checkbox values stay persistent even when switching pages.
With these modifications, the checkbox state should now persist when switching pages in the DataTable.
Let me know if you have any further questions!