Editable DT table with edits only applying after rules were checked

Hello,

I have the following editable DT table. Sepal.Length and Sepal.Width have been restricted so no changes can be made to them. However, Petal.Length needs to be changeable but with rules checking that a valid input was provided. A valid input for Petal.Length by row should not be less than the min value and not more than the max provided as part of the table.

library(shiny)
library(DT)
library(tidyverse)
shinyApp(
  ui = fluidPage(
    DTOutput('x1')
  ),
  server = function(input, output, session) {
    x = reactiveValues(df = NULL)
    
    observe({
      df <- iris
      df <- df %>% mutate(min = 1)
      df <- df %>% mutate(max = max(sample(1:10,5)))
      x$df <- df
    })
    
    output$x1 = renderDT(x$df, selection = 'none', editable = list(target = 'cell', disable = list(columns = c(1,2))))
    
    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$df[i, j] <- isolate(DT::coerceValue(v, x$df[i, j]))
    })
    
    reactive_df <- reactive({
      temp <- x$df %>% mutate(sum = Sepal.Length + Sepal.Width + Petal.Length)
      temp})

  }
)

Hi @GreyMerchant. If you use dataTableProxy, the data table will update the value automatically no matter the original data. You have to use replaceData to update the edited original data.

    observeEvent(input$x1_cell_edit, {
      info = input$x1_cell_edit
      str(info)
      i = info$row
      j = info$col
      v = info$value
      min = as.numeric(x$df[i, 6])
      max = as.numeric(x$df[i, 7])
      
      if (!is.na(v) && v != "") {
        if (j == 3 && as.numeric(v) > min && as.numeric(v) < max) {
          x$df[i, j] <- isolate(DT::coerceValue(v, x$df[i, j]))
        } else if (j != 3) {
          x$df[i, j] <- isolate(DT::coerceValue(v, x$df[i, j]))
        }
      }
      replaceData(proxy, x$df, resetPaging = TRUE)
    })
1 Like

Thank you for this. It was very clear.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.