How to add custom button in R Shiny datatable?

只谈情不闲聊 提交于 2019-12-23 04:56:14

问题


There is an option to add a custom button on datatables.net site. How it can be coded in R Shiny app? A basic R code example for one button and observer will be great to see.

Here is JS code from https://datatables.net/extensions/buttons/examples/initialisation/custom.html

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            {
                text: 'My button',
                action: function ( e, dt, node, config ) {
                    alert( 'Button activated' );
                }
            }
        ]
    } );
} );

Thanks !


回答1:


You don't need to use Javascript, except for the action. You can do:

library(DT)
datatable(iris,
          extensions = 'Buttons',
          options = list(
            dom = 'Bfrtip',
            buttons = list(
              "copy",
              list(
                extend = "collection",
                text = 'test',
                action = DT::JS("function ( e, dt, node, config ) {
                                    alert( 'Button activated' );
                                }")
              )
            )
          )
)

To pass something from Javascript to the shiny server, use Shiny.setInputValue:

library(shiny)
library(DT)

ui <- basicPage(
  DTOutput("dtable")
)

server <- function(input, output, session){
  output$dtable <- renderDT(
    datatable(iris,
              extensions = 'Buttons',
              options = list(
                dom = 'Bfrtip',
                buttons = list(
                  "copy",
                  list(
                    extend = "collection",
                    text = 'test',
                    action = DT::JS("function ( e, dt, node, config ) {
                                      Shiny.setInputValue('test', true, {priority: 'event'});
                                   }")
                  )
                )
              )
    )
  )

  observeEvent(input$test, {
      print("hello")
  })
}

shinyApp(ui, server)



回答2:


I appreciate the answer of Stephane Laurent and found the missing thing. there has to be a pair of brackets {} around

priority: 'event'

like,

Shiny.setInputValue('test', true, {priority: 'event'});

as in https://shiny.rstudio.com/articles/communicating-with-js.html



来源:https://stackoverflow.com/questions/53600956/how-to-add-custom-button-in-r-shiny-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!