This is a follow up of a previous thread I wrote.
I have a simple Shiny App relying on DT::renderDataTable
to generate a table based on the mtcars
dataset.
I have included an action button that enables to expand all rows when pressed (based on the rowGroup
extension).
Since the column index that is used as the rowGroup = list(dataSrc = ColNum)
argument is defined programmatically (ie, ColNum <- 3
), I would like then to pass this integer value from R to javascript as an argument of the action = JS(function())
.
Since my understand of javascript is very limited, I have tried to follow this thread but unsucessfully...
Here is my reproducible example:
library(shiny)
library(DT)
ui <- fluidPage(# Application title
titlePanel("Collapse/Expand table"),
mainPanel(
tabsetPanel(
tabPanel("table1",
# actionButton("expandButton", "Expand/Collapse"),
dataTableOutput("my_table"))
)
))
# Column corresponding to the rowGroup argument
ColNum <- 3
server <- function(input, output, session) {
# Send ColNum to the browser
observe({
session$sendCustomMessage("column-integer", jsonlite::toJSON(ColNum))
})
# Generate the table
output$my_table <- DT::renderDataTable({
datatable(
mtcars[1:15, 1:5],
extensions = c('RowGroup',"Buttons"),
options = list(rowGroup = list(dataSrc = ColNum),
pageLength = 20,
dom = 'tB',
buttons = list(
list(extend = "",
text = "Expand rows",
action = JS("Shiny.addCustomMessageHandler('column-integer', function (e, dt, node, config, ColNum) {dt.rowGroup().dataSrc(ColNum).draw();})")))),
callback = JS(
"table.on('click', 'tr.dtrg-group', function () {",
" var rowsCollapse = $(this).nextUntil('.dtrg-group');",
" $(rowsCollapse).toggleClass('hidden');",
"});",
"table.one('init', () => $('#my_table .dtrg-group').trigger('click'))"
),
selection = 'none'
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Thanks for the support,
C.
I tried to modify
observe({
session$sendCustomMessage("column-integer", jsonlite::toJSON(ColNum))
})
as
observe({
session$sendCustomMessage("column-integer", ColNum)
})
But it had no effect.
You can set ColNum
as a global JavaScript variable and change its value with the Shiny message handler:
js <- "
var ColNum = 3;
$(document).ready(function() {
Shiny.addCustomMessageHandler('column-integer', function(x) {
ColNum = x;
});
});
"
tags$head(tags$script(HTML(js)))
Since ColNum
is a global variable it will be found in the action of the custom button:
function(e, dt, node, config) {
dt.rowGroup().dataSrc(ColNum).draw();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.