-->

edited cell in data table goes back to its origina

2020-04-18 08:27发布

问题:

This is an extension of this post

After I edit any cell in the editable data table, I check/uncheck some column, the cell goes back to its original value.

I have not idea why that happens. Does anyone know how I can fix this? Thank you very much in advance!

library(shiny)
library(DT)
library(dplyr)


    # UI
    ui = fluidPage(DT::dataTableOutput('tbl'),
                   checkboxGroupInput('datacols', 
                                      label='Select Columns:',
                                      choices= c('Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width', 'Specie'),
                                      selected = c('Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width', 'Specie'),
                                      inline=TRUE )

    )

    # SERVER
    server = function(input, output) {



        df = reactiveValues()

        observe ({

            df$dat = iris %>% select(one_of(input$datacols))
        })
        # render DT
        output$tbl = renderDT(server=FALSE, {
            datatable(df$dat,
                      editable = "cell",
                      extensions = "Buttons",
                      options = list(
                          dom = "Bfrtip", buttons = list("csv")))

        })


        observeEvent(input[["tbl_cell_edit"]], {
            cellinfo <- input[["tbl_cell_edit"]]
            df$dat  <- editData(df$dat,  input[["tbl_cell_edit"]])
        })

    }
shinyApp(ui=ui, server = server)

回答1:

We need to select columns when we render the datatable.

    observe ({
                df$dat = iris 
            })
            # render DT
            output$tbl = renderDT(server=FALSE, {
                datatable(df$dat %>% select(one_of(input$datacols)),
                          editable = "cell",
                          extensions = "Buttons",
                          options = list(
                              dom = "Bfrtip", buttons = list("csv")))

            })


标签: r shiny dt