Last active
May 4, 2023 22:40
-
-
Save jonocarroll/6de8d5b4b7dbe33001820ba1939ebac0 to your computer and use it in GitHub Desktop.
Expand/Collapse buttons plus rowcounts and totals for rowGroups in DT::datatable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
ui <- fluidPage( | |
titlePanel("Expand/Collapse DataTable"), | |
mainPanel( | |
fluidRow( | |
column(6, DT::dataTableOutput("tbl")), | |
column(6, DT::dataTableOutput("tbl2")) | |
) | |
) | |
) | |
## start collapsed | |
callback_js <- DT::JS( | |
"table.on('click', 'tr.dtrg-group', function () {", | |
" var rowsCollapse = $(this).nextUntil('.dtrg-group');", | |
" $(rowsCollapse).toggleClass('hidden');", | |
"});", | |
"table.on('init', () => $('.dtrg-group').trigger('click'))" | |
) | |
server <- function(input, output) { | |
set.seed(1) | |
d <- data.frame(Label = c("A", "A", "B", "B", "B", "C", "C", "C", "C"), | |
Value = sample(9)) | |
# Use the ID of the table in the JS. In this example, the first table is DataTables_Table_1 | |
output$tbl <- DT::renderDT({ | |
DT::datatable( | |
d, | |
extensions = c("RowGroup", "Buttons"), | |
options = list( | |
rowGroup = list(dataSrc = 1, | |
startRender = DT::JS("function(rows, group) { | |
var nrows = 0; | |
var total = 0; | |
rows.rows().data().filter(function(value, index) { | |
nrows += value[1] === group ? 1 : 0; | |
total += value[1] === group ? value[2] : 0; | |
}); | |
return group + ' (' + nrows + ' rows; total value: ' + total + ')'; | |
}") | |
), | |
pageLength = 20, | |
dom = 'Bfrtlip', | |
buttons = list( | |
list(extend = "", | |
text = 'Expand <span class="glyphicon glyphicon-plus"></span>', | |
action = DT::JS("() => { | |
$('#DataTables_Table_1').find('.hidden').removeClass('hidden'); | |
}") | |
), | |
list(extend = "", | |
text = 'Collapse <span class="glyphicon glyphicon-minus"></span>', | |
action = DT::JS("() => { | |
$('#DataTables_Table_1').find('.even').addClass('hidden'); | |
$('#DataTables_Table_1').find('.odd').addClass('hidden'); | |
}") | |
) | |
) | |
), | |
callback = callback_js, | |
selection = 'none', | |
escape = FALSE | |
) | |
}) | |
output$tbl2 <- DT::renderDT({ | |
DT::datatable( | |
d, | |
extensions = c("RowGroup"), | |
options = list( | |
rowGroup = list(dataSrc = 1) | |
), | |
callback = callback_js, | |
selection = 'none', | |
escape = FALSE | |
)}) | |
} | |
# Run the application | |
shinyApp(ui = ui, server = server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Additional update: using jQuery
.find('.hidden').removeClass('hidden')
works even better.