For demonstration purposes, I have implemented an example datatable in shiny, where one can search the whole datatable (by using the search field in the top-right corner) and/or within a specific column (by using the search fields above the columns).
The smart search (e.g. searching the whole datatable or the column car for "Ma W" shows "Mazda RX4 Wag") works fine the search fields, when the datatable is processed on the client-side (SERVER = FALSE).
However, if the datatable is processed on the server-side (SERVER = TRUE), the smart search works only for the whole datatable search, but stops working for the column search.
Is there a way to enable smart search also for the columns with server-side processing?
Thank you in advance.
library(DT)
library(shiny)
ui = fluidPage(
fluidRow(
column(width = 12,
DTOutput("dtable")
)
)
)
server = function(input, output, session) {
data = data.frame(
car = c("Mazda", "Mazda RX4", "Mazda RX4 Wag", "Ford", "Mercedes"),
pet = c("dog", "dog", "cat", "cat", "cat")
)
output$dtable = renderDT({
js = c(
"function(settings) {",
" var instance = settings.oInstance;",
" var table = instance.api();",
" var $inputs = instance.parent().find('.form-group input');",
" $inputs.off('keyup search input').on('keyup', function() {",
" var value = $(this).val();",
" if(value !== '') {",
" var index = 1 + $inputs.index(this);",
" var column = table.column(index);",
" column.search(value, false, true, true).draw();", # -> regex, smart, caseInsensitive
" }",
" });",
"}"
)
datatable(
data, filter = "top",
options = list(
dom = "ft",
columnDefs = list(
list(targets = "_all", className = "dt-center")
),
search = list(regex = FALSE, smart = TRUE, caseInsensitive = TRUE), # -> is redundant due to the following up js = c(...) part
initComplete = JS(js)
)
)
}, server = FALSE) # -> switch for client-side (server=FALSE) or server-side (SERVER=TRUE) processing
}
shinyApp(ui = ui, server = server)
2
Answers
Since the smart-search logic is still working for the whole datatable search while processing the data on the server-side (SERVER=TRUE), I had to adapt the column search in order to receive an OR-logic (smart-search logic) the following way:
Smart search on individual columns is currently not implemented in
DT
for the server mode. However, you can add the functionality by implementing your own search function by following these two steps:DT:::dataTablesFilter
. This function has to be modified. CallThen a window will open where you change the part (currently approximately around line 45):
to this one:
Save this and it should work while having
server = TRUE
. Then your custom function is called when searching and the smart search is enabled viasmart = TRUE
what you already defined in your code. Also notice that you have to disable yourjs
and that this approach also should work forserver = FALSE
.