R语言 shinyvalidate -插入UI后不会出现警告消息

toiithl6  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(101)

我有一个漂亮的应用程序,它可以根据用户的选择动态地删除和插入输入UI。选择choice1choice2生成的UI共享了它们的部分输入字段。我想使用shinyvalidate包来添加一些验证规则,这些规则可以应用于共享的输入。在下面的示例中,用户可以在侧边栏上进行选择。一旦做出选择,主面板上ID为“content”的div将被删除,并插入一个新的div。规则似乎起作用了,但除非我先在输入字段中键入一些内容,否则当我切换选项时,红色警告消息不会出现。

library(shiny)
library(glue)
library(shinyvalidate)

ui <- fluidPage(
  sidebarPanel(
  selectInput("select", label = "select", choices = c("", "choice1", "choice2"))
  ),
  mainPanel(id = "main",
            tags$div(id = "content"))
)

server <- function(input, output) {

  # validate input
  iv <- InputValidator$new()
  iv$add_rule("input", sv_required())
  iv$enable()

  
  
  observeEvent(input$select, {
  
    if(input$select == "choice1"){
      removeUI("#content")
      insertUI("#main", ui = tags$div(
        id = "content", 
        textInput("input", "input")))
    } 
    if(input$select == "choice2"){
      removeUI("#content")
      insertUI("#main", ui = tags$div(
        id = "content", 
        textInput("input", "input")))
    }

      })
  

}

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

6gpjuf901#

这是通过在observeEvent完成其工作后触发iv$enable来实现的(我认为“无效”是正确的措辞)。

server <- function(input, output) {
  
  # validate input
  iv <- InputValidator$new()
  iv$add_rule("input", sv_required())
  
  Validate <- reactiveVal(NULL)
  
  observeEvent(input$select, {
    
    iv$disable()
    
    if(input$select == "choice1"){
      removeUI("#content")
      insertUI("#main", ui = tags$div(
        id = "content", 
        textInput("input", "input")))
    } 
    if(input$select == "choice2"){
      removeUI("#content")
      insertUI("#main", ui = tags$div(
        id = "content", 
        textInput("input", "input")))
    }
    
    Validate(TRUE)
    
  })
  
  observeEvent(Validate(), {
    iv$enable()
    Validate(NULL)
  })
  
}

编辑

我不知道为什么,但您必须在removeUIinsertUI中设置immediate = TRUE

if(input$select == "choice1"){
      removeUI("#content", immediate = TRUE)
      insertUI("#main", ui = tags$div(
        id = "content", 
        textInput("input", "input")), immediate = TRUE)
    } 
    if(input$select == "choice2"){
      removeUI("#content", immediate = TRUE)
      insertUI("#main", ui = tags$div(
        id = "content", 
        textInput("input", "input")), immediate = TRUE)
    }

相关问题