I'm trying to change cell color of column 'R/Y/G' as soon as values of column 'R', 'Y' or 'G' is changed. I have made the datatable editable for that reason. The color changes, but only when I edit a cell value and close the app and reopen it again. But it doesn't change as soon as I edit the cell value. Here's my code :
dt_output = function(title, id) {
fluidRow(column(
12, h1(paste0(title)),
hr(), DTOutput(id)
))
}
render_dt = function(data, editable = 'cell', server = TRUE, ...) {
renderDT(data,selection = 'none', server = server, editable = editable, ...)
}
ui = fluidPage(
downloadButton("mcp_csv", "Download as CSV", class="but"),
dt_output('Report', 'x9')
)
server = function(input, output, session) {
d1 = readRDS("cmp.rds")
d9 = d1
observeEvent(input$x9_cell_edit, {
d9 <<- editData(d9, input$x9_cell_edit, 'x9', rownames = FALSE)
saveRDS(d9, 'cmp.rds', version = 2)
})
d9$tcolor <- ifelse(d9$R > 2500000, 2,
ifelse(d9$Y > 2000000 & d9$Y <= 2500000, 0,
ifelse(d9$G <= 2000000, 1)))
dt_d9=datatable(d9, editable = 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis'))) %>% formatStyle(
'R/Y/G', 'tcolor',
backgroundColor = styleEqual(c(0,1,2), c('yellow', 'green', 'red')),fontWeight = 'bold'
)
output$x9 = render_dt(dt_d9)
Based on ideas found here, here's the server part, storing the dataframe in a reactiveValues()
:
server = function(input, output, session) {
d1 = readRDS("cmp.RDS")
d9 = d1
d9$tcolor <- NA
rv <- reactiveValues()
observe({
rv$d9 <- d9
})
dt_d9=datatable(isolate(d9), editable = 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis'))) %>% formatStyle(
'R/Y/G', 'tcolor',
backgroundColor = styleEqual(c(0,1,2), c('yellow', 'green', 'red')),fontWeight = 'bold'
)
output$x9 = render_dt(dt_d9)
proxy = dataTableProxy('x9')
observe({
DT::replaceData(proxy, rv$d9, rownames = FALSE, resetPaging = FALSE)
})
observeEvent(input$x9_cell_edit, {
rv$d9 <<- editData(rv$d9, input$x9_cell_edit, 'x9', rownames = FALSE)
d9 <- rv$d9
d9$tcolor <- ifelse(d9$R > 2500000, 2,
ifelse(d9$Y > 2000000 & d9$Y <= 2500000, 0,
ifelse(d9$G <= 2000000, 1)))
rv$d9 <<- d9
saveRDS(d9, 'cmp.rds', version = 2)
})
}