My goal is to have a dropdown menu in a column of datatable and make the table editable for other columns as well.
I find this solution for my first requirement and datatable can be edited by putting editable = TRUE
.
I am able to do both the things separately with no issues, but I am not able to do both the things together.
library(shiny)
library(DT)
ui <- fluidPage(
title = 'Selectinput column in a table',
h3("Source:", tags$a("Yihui Xie", href = "https://yihui.shinyapps.io/DT-radio/")),
DT::dataTableOutput('foo'),
verbatimTextOutput('sel')
)
server <- function(input, output, session) {
data <- head(iris, 5)
# adding column having dropdown items
for (i in 1:nrow(data)) {
data$species_selector[i] <- as.character(selectInput(paste0("sel", i), "", choices = unique(iris$Species), width = "100px"))
}
## output for data table
output$foo = DT::renderDataTable(
data,
escape = F,
editable = T,
selection = 'none',
server = F, # we need it to be TRUE.
options = list(dom = 't', paging = FALSE, ordering = FALSE)
,callback = JS("table.rows().every(function(i, tab, row) {
var $this = $(this.node());
$this.attr('id', this.data()[0]);
$this.addClass('shiny-input-container');
});
Shiny.unbindAll(table.table().node());
Shiny.bindAll(table.table().node());")
,rownames = F
)
# saving the proxy of table
proxy = dataTableProxy('foo')
text <- reactive({
# browser()
(sapply(1:nrow(data), function(i) input[[paste0("sel", i)]]))
})
output$sel = renderPrint({
# data$species_selector[1]
text()
})
# this chunk is for update the table for changes done in ui. "This is a must have"
observeEvent(input$foo_cell_edit, {
info = input$foo_cell_edit
str(info)
i = info$row
j = info$col + 1 # column index offset by 1
v = info$value
data[i, j] <<- DT::coerceValue(v, data[i, j])
# replacing the data in the proxy
replaceData(proxy, data, resetPaging = FALSE, rownames = FALSE)
})
}
shinyApp(ui, server)
When I put server = T
I can edit the table with no issues but I can not get the selected values of dropdown menu (which I need). And when I put server = F
then I get the selected values of dropdown but then when I try to edit my table it shows error as "DataTables warning: table id=DataTables_Table_0 - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"
Any help or direction is highly appreciated.
Note: I know these both operations are very easy in rhandsontable, I am not using it because it has other limitations like search button, conditional formatting etc.