Nehau
Nehau

Reputation: 11

How to add arguments to a datatable based on some if conditions?

I am trying to format a table in shiny using DT::datatable. All my tables can have the default container but only when I pass the container argument that is when I want it to be designed as passed. I have tried multiple options of using if conditions but to no avail. WHen I looked at the datatable code, it says that if the container function is missing it takes a default type. I tried to coerce the same as well but it is still giving me an error.

Please help on this. Below is the code for the same:

table_opt = function(x, edit_y, container_dat = NULL, form_type = "", col_list = NULL){
  
  DT::renderDataTable({
    
    ####### Percentage Format
    
    if(form_type == "%")
    {
      datatable(x
                ,editable = edit_y
                ,if(is.null(container_dat)){container = expr()} else {container = container_dat}
                ,rownames = F
                ,options = list(
                  paging = F
                  ,ordering = F
                  ,searching = F
                  ,deferRender = T
                  ,class = "compact"
                  ,headerCallback = JS(
                    "function(thead) {",
                    "$(thead).css('font-size','14px');",
                    "$(thead).css('background-color','#000000');",
                    "$(thead).css('color','#ffffff');",
                    "}"
                  ,columnDefs = list(list(className = 'dt-center', targets = '_all'))
                )) %>%
                formatPercentage(col_list,digits = 2)
    }
})
}

Upvotes: 1

Views: 271

Answers (1)

mosk915
mosk915

Reputation: 814

do.call should accomplish what you're trying to do.

table_opt = function(x, edit_y, container_dat = NULL, form_type = "", col_list = NULL){
  
  DT::renderDataTable({
    
    ####### Percentage Format
    
    if(form_type == "%")
    {
      dt_args <- list(data = x
                      ,editable = edit_y
                      ,rownames = F
                      ,options = list(
                        paging = F
                        ,ordering = F
                        ,searching = F
                        ,deferRender = T
                        ,class = "compact"
                        ,headerCallback = JS(
                          "function(thead) {",
                          "$(thead).css('font-size','14px');",
                          "$(thead).css('background-color','#000000');",
                          "$(thead).css('color','#ffffff');",
                          "}"
                          ,columnDefs = list(list(className = 'dt-center', targets = '_all'))
                        ))
      )
      
      if(!is.null(container_dat)) dt_args$container <- container_dat
      
      do.call("datatable", dt_args) %>%
        formatPercentage(col_list,digits = 2)
    }
  })
}

Upvotes: 0

Related Questions