Show validate error message only once

狂风中的少年 提交于 2020-01-05 04:28:12

问题


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?


回答1:


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)
            })

    })


来源:https://stackoverflow.com/questions/40548508/show-validate-error-message-only-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!