2

I have a rhandsontable in a shiny app, that has 2 rows. It uses reactiveValues() to load values inside of it. Creating additional rows by dragging a cell is prohibited with

fillHandle = list(direction='vertical', autoInsertRow=FALSE))

The user should be allowed to create additional rows through context menu, but no more than 10. I though of doing it with customOpts, where the user can add new rows untill nrow(table) == 10, but i'm very bad with javascript. I tried to do it differently (see the code below), but couldn't make it work. Also, is there a way to do it in another way?

Here is the snipped of code I have so far:

output$table <- renderRHandsontable({
  rhandsontable(data.frame(rv_values),
                fillHandle = list(direction='vertical', autoInsertRow=FALSE)) %>%
    hot_context_menu(allowRowEdit = TRUE, allowColEdit = FALSE)
})

I tried to manually change the allowRowEdit like this, but couldn't quite figure out how to make it work:

observeEvent(input$table, {
  if(nrow(hot_to_r(input$table)) > 10)
#magic happens here

})

Any ideas?

vladli
  • 1,454
  • 2
  • 16
  • 40

2 Answers2

2

I'm sorry I asked that question too quickly. After spending 2 hours on that and posting it here, I found a simple solution: add maxRows = 10 to rhandsontable, and that's it.

 rhandsontable(data.frame(rv_data),
                fillHandle = list(direction='vertical', autoInsertRow=FALSE),
                maxRows = 10) %>%
    hot_context_menu(allowRowEdit = TRUE, allowColEdit = FALSE)
vladli
  • 1,454
  • 2
  • 16
  • 40
  • That's a more elegant solution than mine. ;) I was unfamiliar with the rhandsontable package, so created my own solution.. – Florian Jul 21 '17 at 12:02
  • Sad thing is that there is nothing about it in documentation, and hardly any examples of `customOpts` usage. – vladli Jul 21 '17 at 14:00
1

Does this do what you want? It doesn't use Javascript, but it let's the user add rows, until the maximum is reached:

max_rows = 5

require(shiny)
library(DT)

ui<-shinyUI(
  fluidPage(
    actionButton("action","Add row"),
    rHandsontableOutput("table")

  )
)

server <- function(input, output, session) {

  rv_values <- reactiveVal()
  rv_values(head(mtcars,3))


  observeEvent(input$action,{
    if(!nrow(rv_values())==5)
    {
      rv_values(head(mtcars,nrow(rv_values())+1))    
    }
    else
    {
      showModal(modalDialog(
        title = "Important message",
        "Already reached maximum number of rows!"
      ))
    }
  }
  )

  output$table <- renderRHandsontable({
    rhandsontable(data.frame(rv_values()),
                  fillHandle = list(direction='vertical', autoInsertRow=FALSE)) %>%
      hot_context_menu(allowRowEdit = TRUE, allowColEdit = FALSE)
  })

}

shinyApp(ui,server)

Hope this helps!

Florian
  • 24,425
  • 4
  • 49
  • 80