Disable edit of specific cell DT

51 Views Asked by At

Is it possible to only disable the edit of a specific cell (by column- and rowindex) using RShiny DT?

E.g. in the next code sample, only the cell which contains 'Mary' should be disabled. All other cells should be editable.

library(shiny)
library(DT)

# Sample data (you can replace this with your own dataset)
dat <- data.frame(
  userName = c("John", "Mary", "Mike"),
  start = c("06/08/2019", "01/01/2019", "23/10/2019"),
  stringsAsFactors = FALSE
)

ui <- fluidPage(
  titlePanel("Editable Datatable Example"),
  DTOutput("userTable")
)

server <- function(input, output, session) {
  output$userTable <- renderDT({
    datatable(dat, editable = TRUE, rownames = FALSE)
  })
  
  observeEvent(input$userTable_cell_edit, {
    # Handle cell edits here (e.g., update the underlying data)
    # For demonstration purposes, we'll just print the edited value
    cat("Edited value:", input$userTable_cell_edit$value, "\n")
  })
}

shinyApp(ui = ui, server = server)
1

There are 1 best solutions below

0
thothal On

One of these hacks would be to add an event handler listening on dblclick on the specific cell which stops the event from reaching the handler which fires the edit dialogue:

datatable(dat, 
         editable = TRUE, 
         rownames = FALSE,
         options = 
           list(
             columnDefs = 
               list(
                 list(
                   targets = 0, 
                   createdCell = 
                     JS("function (td, cellData, rowData, row, col) {
                           if (row == 1) {
                             $(td).on('dblclick', function(e) {
                               e.stopPropagation()
                             })
                           }
                         }")
                 )
               )
           )
)

It is a very fragile hack (especially because it only prevents double clicks and does not switch off editing per se, that is if there is any other method to edit the cell this is not prevented with this hack) and you should think carefully how to address the cell properly. I used createCell in columnDefs to add the event handler. It is important that you add the listener somewhere below <table>, because there the edit handler sits. So we want to attach a listener below to be able to prevent the event from bubbling up.

To make a long story short, there are a plethora of reasons why you should not use this hack, but it can be done at least.