RoyalTS
RoyalTS

Reputation: 10203

Show validate error message only once

Take this example app from the shiny docs that shows the working of the validate() function:

## server.R

`%then%` <- shiny:::`%OR%`

shinyServer(function(input, output) {

  data <- reactive({
    validate(
      need(input$data != "", "Please select a data set") %then%
      need(input$data %in% c("mtcars", "faithful", "iris"),
        "Unrecognized data set") %then%
      need(input$data, "Input is an empty string") %then%
      need(!is.null(input$data),
        "Input is not an empty string, it is NULL")
    )
    get(input$data, 'package:datasets')
  })

  output$plot <- renderPlot({
    hist(data()[, 1], col = 'forestgreen', border = 'white')
  })

  output$table <- renderTable({
    head(data())
  })

})

## ui.R

shinyUI(fluidPage(

  tags$head(
    tags$style(HTML("
      .shiny-output-error-validation {
        color: green;
      }
    "))
  ),

  titlePanel("Validation App"),

  sidebarLayout(
    sidebarPanel(
      selectInput("data", label = "Data set",
        choices = c("", "mtcars", "faithful", "iris"))
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("plot"),
      tableOutput("table")
    )
  )
))

Is there any way to only make the app display the validate error message once instead of twice because the same validate fails once for the plot and once for the table element?

Upvotes: 0

Views: 602

Answers (1)

Valter Beaković
Valter Beaković

Reputation: 3250

I guess there should be a better way to solve this, but this is the only idea that I had:

server.R

     ## server.R

    `%then%` <- shiny:::`%OR%`

    shinyServer(function(input, output) {
            values <- reactiveValues(test=data.frame())
            data <- reactive({
                    validate(
                            need(input$data != "", "Please select a data set") %then%
                                    need(input$data %in% c("mtcars", "faithful", "iris"),
                                         "Unrecognized data set") %then%
                                    need(input$data, "Input is an empty string") %then%
                                    need(!is.null(input$data),
                                         "Input is not an empty string, it is NULL")
                    )
                    get(input$data, 'package:datasets')
            })
            observeEvent(data(), {
                    if(!is.null(data())) {
                            values$test <- data()
                    } else {
                            values$test <- NULL
                    }
            })

            output$plot <- renderPlot({
                    hist(data()[, 1], col = 'forestgreen', border = 'white')
            })

            output$table <- renderTable({
                    head(values$test)
            })

    })

Upvotes: 2

Related Questions