Anshu
Anshu

Reputation: 21

Error message for empty table for DT::renderDataTable in R

I have a requirement to show data coming from table on UI screen. I am currently using DT::renderDataTable.

Inside renderDataTable, the code will return data that is getting returned from a table. Incase there is no Data available in the table, blank is displayed on screen.

I need to add some custome error message when there is no data in the table, can you please help.

Upvotes: 1

Views: 4006

Answers (2)

Justace Clutter
Justace Clutter

Reputation: 2186

I know this question is quite stale, but thought I would put this answer up here for other people searching for a solution.

Add the following to the call to Datatable or renderDataTable

options = list(language = list(emptyTable = 'My Custom No Data Message'))

Also, pass a zero row data frame to the renderDataTable so it knows how to setup the columns. You can get a zero row data frame in the following way:

If you dont have an existing data frame:

data.frame(ColOne=numeric(), ColTwo=character(), ColThree=numeric, stringsAsFactors=FALSE)

If you do have an existing data frame:

myexistingdf[NULL,]

Upvotes: 3

JohnCoene
JohnCoene

Reputation: 2261

There are different ways about it.

Show a notification

library(DT)
library(shiny)

ui <- fluidPage(
    actionButton("load", "Load/unload data"),
    DTOutput("table")
)

server <- function(input, output, session) {
    df <- eventReactive(input$load, {
        if(input$load %% 2 == 0){
            return(cars)
        } else {
            shiny::showNotification("No data", type = "error")
            NULL
        }
    })

    output$table <- renderDT(df())
}

shinyApp(ui, server)

Show error

library(DT)
library(shiny)

ui <- fluidPage(
    actionButton("load", "Load/unload data"),
    DTOutput("table")
)

server <- function(input, output, session) {
    df <- reactive({
        if(input$load %% 2 == 0){
            dat <- cars
        } else {
            dat <- NULL
        }

        validate(
            need(!is.null(dat), "No data")
        )

        return(dat)
    })

    output$table <- renderDT(df())
}

shinyApp(ui, server)

You could also show a modal with showModal.

Upvotes: 5

Related Questions