Is there any way to add custom R-function action to a button in DT?

Viewed 896

I'm trying to add a custom button performing the action defined by R-function to my datatable. I've used the same list of options in my R code as in Javascript code in Datatables manual, but it doesn't work.

Here is a code from Datatables manual:

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

And here is my code in R:

require(DT)
DT::datatable(iris,
    extensions = 'Buttons',
    options = list(
        dom = 'Bfrtip',
        buttons = list(
            list(
                text = 'test',
                action = print('1')
                )
        )
    )
)

Executing it I've received an error:

Error in if (extend != "collection") extend else listButtons(cfg) : 
  argument is of length zero
1 Answers

You have to set extend = "collection", like this:

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' );
                                }")
              )
            )
          )
)

But the action can only execute some Javascript, not a R command. However you can execute a R command by clicking a custom button if you put the datatable in a shiny application. Something like that:

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);
                                   }")
                  )
                )
              )
    )
  )

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

shinyApp(ui, server)
Related