0

I am trying to develop a shiny app that will allow users to add, delete and save edits to a DT table with the editable settings enabled. However for some reason I am not being able to add a row. Anybody has any clues as to why this is happening?

I am using the iris dataset as an example. (saveRDS(iris,"iris.rds"))

library(shiny)
library(DT)


shinyApp(
  ui = fluidPage(
    DTOutput('x1'),
    actionButton("save", "Save Table"),
    actionButton("add_btn","Add Button")
  ),
  server = function(input, output, session) {
    x <- readRDS("iris.rds")
    output$x1 = renderDT(x, selection = 'none', editable = TRUE)
    
    proxy = dataTableProxy('x1')
    
    observeEvent(input$x1_cell_edit, {
      info = input$x1_cell_edit
      str(info)
      i = info$row
      j = info$col
      v = info$value
      x[i, j] <<- DT::coerceValue(v, x[i, j])
      replaceData(proxy, x, resetPaging = FALSE) }) 
    
    observeEvent(input$add_btn, 
                 {newrow <- setNames(data.frame(matrix(ncol = ncol(x), nrow = 1)),
                                     colnames(x))
                 x<<-rbind(x,newrow)})
    
    observeEvent(input$save,
                 {saveRDS(x, "iris.rds")
                 })
  }
)
Sahib
  • 160
  • 8

1 Answers1

1

You were using values$data an unknown data.frame instead of using x, and u weren't updating the DT output using the replaceData function:

observeEvent(input$add_btn, 
     {  newrow <- setNames(data.frame(matrix(ncol = ncol(x), nrow = 1)),
                                     colnames(x))
        x<<-rbind(x,newrow)
        replaceData(proxy, x, resetPaging = F)
     })
Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21