vagelis
vagelis

Reputation: 464

Replace options in R Shiny datatable on the fly

I would like to change the language of a datatable on the fly

I have the following code

output$prr2 <- renderDataTable({  
prr()}, options = list(
autoWidth = TRUE,
columnDefs = list(list(width = '50', targets = c(1, 2) ) ),
language = list(url = if(getLanguage()=='gr') '//cdn.datatables.net/plug-ins/1.10.11/i18n/Greek.json' else  
  '//cdn.datatables.net/plug-ins/1.10.11/i18n/English.json' ))

getLanguage() returns the value of selected_language, prr() returns a data.frame.

I want to do something like this in order to change options of the table after selecting a different language in a dropdown selected_language

proxy = dataTableProxy('prr2')
observeEvent(input$selected_language,{ replace language option of datatable prr2})

Any idea about this?

Upvotes: 0

Views: 241

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

I can't test since you don't provide a reproducible example. I would try

output$prr2 <- renderDataTable({  
  prr()
}, options = exprToFunction(list(
  autoWidth = TRUE,
  columnDefs = list(list(width = '50', targets = c(1, 2))),
  language = list(
    url = ifelse(getLanguage()=='gr', 
                 '//cdn.datatables.net/plug-ins/1.10.11/i18n/Greek.json', 
                 '//cdn.datatables.net/plug-ins/1.10.11/i18n/English.json')
  )
)))

EDIT

output$prr2 <- renderDataTable({  
  datatable(
    prr(),
    options = exprToFunction(list(
      autoWidth = TRUE,
      columnDefs = list(list(width = '50', targets = c(1, 2))),
      language = list(
        url = ifelse(getLanguage()=='gr', 
                     '//cdn.datatables.net/plug-ins/1.10.11/i18n/Greek.json', 
                     '//cdn.datatables.net/plug-ins/1.10.11/i18n/English.json')
      )
    )
    )
  )
})

EDIT 2

Full app which works:

library(shiny)
library(DT)

ui <- fluidPage(
  radioButtons("language", "Language", choices = c("gr", "en")),
  DTOutput("prr2")
)

server <- function(input, output, session){
  output$prr2 <- renderDT({  
    datatable(
      iris,
      options = exprToFunction(list(
        autoWidth = TRUE,
        columnDefs = list(list(width = '50', targets = c(1, 2))),
        language = list(
          url = ifelse(input$language=='gr', 
                       '//cdn.datatables.net/plug-ins/1.10.11/i18n/Greek.json', 
                       '//cdn.datatables.net/plug-ins/1.10.11/i18n/English.json')
        )
      ))
    )
  })
}

shinyApp(ui, server)

Upvotes: 2

Related Questions