How to save sorting in dataTable in shiny?

前端 未结 1 1254
栀梦
栀梦 2021-01-18 10:52

I have table on page with possible sorting in columns, by after I reload data with reactive table isn\'t sorted again, here the server.R code:

    library(sh         


        
相关标签:
1条回答
  • 2021-01-18 11:20

    The best way to retain sort order (and selection) is to use proxyDataTable and replaceData to update your data, rather than creating a new table each time the data is updated:

    mydata = reactive({
        df$ID <<- c(df$ID[n], df$ID[-n])
        df
      })
      output$foo = DT::renderDataTable(isolate(mydata()))
      proxy = dataTableProxy('foo')
    
      observe({
        replaceData(proxy, mydata(), resetPaging = FALSE)
      })
    

    There are a couple things to be aware of though. If you are using modules, check out this thread to make sure you are passing the right session variable to the proxy: https://github.com/rstudio/DT/issues/359

    Also, if you use rownames=false for your datatable, you must also pass the parameter to replaceData.

    If proxyDataTable is not an option, you can also use callbacks in DT::renderDataTable:

    #include some javascript
    tags$head(tags$script(src="my.js"))
    
    #options to renderDataTable
     preDrawCallback = JS("initTableOrder"),
     drawCallback = JS("saveTableOrder")
    

    The javascript functions in my.js (stored in your www directory):

    var tableSortOrderSave;
    
    function initTableOrder(settings, json) {   
      if(tableSortOrderSave === undefined){
        $(this.api().table().order());
      }else{
        $(this.api().table().order(tableSortOrderSave));
      }
    }
    
    function saveTableOrder(settings, json) {
      order  = $(this.api().table().order());
      if(order.length > 0){
        tableSortOrderSave = order;
      }
    }
    
    0 讨论(0)
提交回复
热议问题