jrowen / rhandsontable

A htmlwidgets implementation of Handsontable.js
http://jrowen.github.io/rhandsontable/
Other
383 stars 148 forks source link

How to deselect row? #420

Closed jernest1 closed 1 year ago

jernest1 commented 1 year ago

How can I detect when a user deselects a row? In this example, when I click a row, I can detect the selection with input$mytable_select$select$r, but when I click outside the table, input$mytable_select$select$r is still set to the row number.

require(shiny)
require(rhandsontable)
shinyApp(
  ui = fluidPage(
    rHandsontableOutput("mytable")
  ),
  server = function(input, output, session) {
    output$mytable <- renderRHandsontable({
      rhandsontable(
        data = mtcars,
        selectCallback = T
      )
    })

    observe({
      if(is.null(input$mytable_select$select$r)) {
        print("No rows selected")
      } else {
        print(paste0("Selected row: ", input$mytable_select$select$r))
      }
    })

  }
)
jernest1 commented 1 year ago

I found a solution based on a handsontable issue discussion (https://github.com/handsontable/handsontable/issues/902). I can pass a javascript function to a parameter 'afterDeselect' which sets a Shiny input value to a new random value after the table is deselected, then observing this value in Shiny. Alternatively, I can modify the javascript function to set input$mytable_select to NULL and detect that the value is NULL using an observer.

require(shiny)
require(rhandsontable)
shinyApp(
  ui = fluidPage(
    rHandsontableOutput("mytable")
  ),
  server = function(input, output, session) {

    output$mytable <- renderRHandsontable({
      rhandsontable(
        data = mtcars,
        selectCallback = T,
        afterDeselect = htmlwidgets::JS(
          "function() {Shiny.onInputChange('hotDeselect', Math.random())}"
        )
      )
    })

    observeEvent(input$hotDeselect, {
      print("Table was deselected!")
    })

    observe({
      if(is.null(input$mytable_select$select$r)) {
        print("No rows selected")
      } else {
        print(paste0("Selected row: ", input$mytable_select$select$r))
      }
    })

  }
)