【问题标题】:Using validation in an action button在操作按钮中使用验证
【发布时间】:2021-06-13 06:31:48
【问题描述】:

我对 R Shiny 中 req 和 validate 之间的区别有点困惑。我能看到的唯一真正的区别是 validate 向用户发送了一条消息。我正在构建一个界面,并使用了一堆隐藏的消息和条件语句。我想压缩我的代码并喜欢使用 validate 的想法。我只想在用户尝试单击按钮并尝试继续访问 UI 的另一部分时显示我的消息。

我提供了一个简化版的代码,“成功”的消息只会在 id 和协议按钮的文本输入被点击时显示。如果缺少一个或两个,条件面板将显示验证文本。

我担心在操作按钮内显示输出会破坏环境并实质上将其变成反应式环境。我在验证检查后使用了 req,因此除非为两者都提供了输入,否则不会显示成功消息。这是最好的方法吗?还是有更有效/更合适的方法?我主要担心的是,当我构建复杂性时,我会破坏应用程序。

library(shiny)

ui <- fluidPage(
      
      
      textInput(inputId = "id",
                label = 'Please enter your id'
                  ),
      
    
      checkboxInput("agree", label = "I agree", value = FALSE),
      conditionalPanel(condition = "input.id == '' || !input.agree",
                              
                      textOutput('error_msg')
      ),
      
      actionButton("submit_info", "Submit"),
      textOutput('success_msg')
   
  
)

server <- function(input, output) {
  observeEvent(input$submit_info, {
    output$error_msg <- renderText({
      shiny::validate(
        shiny::need(input$id != '', 'You must enter your id above to continue.'
        ),
        shiny::need(input$agree, "You must agree to continue")
      )
      
    })
    
    shiny::req(input$id)
    shiny::req(input$agree)
    output$success_msg <- renderText({"Success"})
  
})
}

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r validation shiny action-button req


    【解决方案1】:

    更新:我已经解决了这个问题。本质上,我只在单击按钮并将验证移到观察事件之外时才显示条件面板。代码如下:

    library(shiny)
    
    ui <- fluidPage(
          
          
          textInput(inputId = "id",
                    label = 'Please enter your id'
                      ),
          
        
          checkboxInput("agree", label = "I agree", value = FALSE),
          conditionalPanel(condition = "(input.submit_info >= 1) & ((input.id == '') || (!input.agree))",
                                  
                          textOutput('error_msg')
          ),
          
          actionButton("submit_info", "Submit"),
          textOutput('success_msg')
       
      
    )
    
    server <- function(input, output) {
      
      output$error_msg <- renderText({
        shiny::validate(
          shiny::need(input$id != '', 'You must enter your id above to continue.'
          ),
          shiny::need(input$agree, "You must agree to continue")
        )
        
      })
      
      observeEvent(input$submit_info, {
        
        shiny::req(input$id)
        shiny::req(input$agree)
        output$success_msg <- renderText({"Success"})
      
    })
    }
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      相关资源
      最近更新 更多