R Shiny:条件成功或错误消息取决于 NULL 值

RShiny: conditional success or error message depending on NULL values

我正在尝试将 actionBttnsendSweetAlert 一起用于一个闪亮的项目。此外,我希望在输入无效时通知用户(例如空白文本输入)。

为此,我尝试在 observeEvent 中使用 validate,这可以防止出现警报,但不会提供替代消息,例如 "Please provide a text"。

这是一个简单的例子:

library(shiny)
library(shinyWidgets)


ui <- fluidPage(
  useSweetAlert(),
  sidebarPanel(
    textInput("text", "Require This Text"),
  actionBttn(
    inputId = "submit",
    label = "Submit Form",
    color = "success",
    style = "float",
    block = TRUE)
  )

)

server <- function(input, output, session) {

  observeEvent(input$submit,
               {
                 validate(
                   need(input$text, message = "Please provide a text")
                 )
                 sendSweetAlert(
                   session = session,
                   title = "Plz halp",
                   text = "Cool stuff doing neat things",
                   type = "success",
                   btn_labels = c("Great")
                 )}
               )
}

# Run the application 
shinyApp(ui = ui, server = server)

请注意,如果没有文本输入,SweetAlert 功能将不起作用(这是件好事),但没有替代消息。

有没有一种干净的方法来做到这一点?我考虑过一个 if 语句来在任何值为 NULL 的情况下显示 SweetAlert 错误,但我不太明白该怎么做。

您可以使用isTruthy检查输入是否填写:

  observeEvent(input$submit,
               if(isTruthy(input$text)) {
                 sendSweetAlert(
                   session = session,
                   title = "Plz halp",
                   text = "Cool stuff doing neat things",
                   type = "success",
                   btn_labels = c("Great")
                 )
               } else {
                 sendSweetAlert(
                   session = session,
                   title = "Plz halp",
                   text = "Please Provide Text",
                   type = "error",
                   btn_labels = c("Sorry!")
                 )
               })

编辑:根据您的评论,您的代码执行类似这样的操作以避免重复。在全球或其他地方,.ake 一个将验证列表的函数

allTruthy <- function(l) {
    all(vapply(l, isTruthy, logical(1)))
}

然后在您的服务器中,将您的表单数据设为反应列表:

  t1Form <- reactive(list(
    pop_interest = input$t1_pop_interest,
    int_interest = input$t1_int_interest,
    comparator = input$t1_comparator,
    poutcome = input$t1_poutcome,
    setting = input$t1_setting
  ))

现在您的表单数据在一个很好的列表中以供使用和验证。那么你的观察者可以是:

  observeEvent(input$submit,
           if(allTruthy(t1Form())) {
             sendSweetAlert(
               session = session,
               title = "Plz halp",
               text = "Cool stuff doing neat things",
               type = "success",
               btn_labels = c("Great")
             )
           } else {
             sendSweetAlert(
               session = session,
               title = "Plz halp",
               text = "Please Provide Text",
               type = "error",
               btn_labels = c("Sorry!")
             )
           })