Как я могу использовать выходные данные selectInput внутри блока insertUI для изменения HTML-кода, генерируемого insertUI? - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь вставить пользовательский интерфейс, который реагирует на selectInput в том же блоке insertUI. Концептуально, insertUI действует как форма, которая представляет selectInput для пользователя, и на основании его / ее выбора затем представляется сопутствующий selectizeInput. Идея состоит в том, что эти два виджета принадлежат одному и тому же выходному элементу div, который может быть удален с помощью одной и той же кнопки removeUI, если пользователь этого пожелает.

Я установил здесь , иЯ пытался адаптировать этот ответ к относительно похожему вопросу, но все мои попытки сломали приложение, когда я нажимал «Добавить новую форму», возвращая следующее предупреждение:

Warning: Error in if: argument is of length zero
  88: tag
  87: tags$div
  86: div
  85: column
  76: observeEventHandler [~/.active-rstudio-document#33]
   5: runApp
   3: print.shiny.appobj
   1: source

Я подозреваю, что моя проблема в том, что я пытаюсь получить входное значение объекта, который не был полностью создан. Я надеялся, что это не будет проблемой, ожидая, что selectizeInput будет отображаться на основе значения по умолчанию для selectInput, и что если и когда пользователь изменит выбор selectInput, selectizeInput будет перерисован заново. Больше не уверен, если это возможно с insertUI (и более задача для renderUI). Мне еще предстоит многое узнать о реактивности, и, возможно, есть более простой способ приблизиться к этому.

Это упрощенная версия моей последней попытки:

library(shiny)
library(shinyjs)
library(shinyWidgets)

ui <- navbarPage(
                  tabPanel(
                          useShinyjs(),
                          hr(),
                          h3("Click the button to add a new form:"),
                             fluidRow(
                               actionBttn(
                                 inputId = "new_form", 
                                 label = "Add new form",
                                 color = "primary",
                                 style = "simple",
                                 size = "sm"
                                 )
                               ),
                             fluidRow(div(id = 'placeholder_new_form'))
                          )
)

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

  observeEvent(input$new_form, {

    # make ids for the plot, the remove button, and the element to remove
    id_add <- paste0("id_", input$new_form)
    remove_id <- paste0("remove_", input$new_form)
    ele_id <- paste0("ele_", input$new_form)
    choice_id <- paste0("choice_", input$new_form)

    insertUI(
      selector = "#placeholder_new_form",
      where = "afterEnd", 
      ui = tags$div(
        id = ele_id,
        fluidRow(
          column (
            width = 6, 
            align = "center",
            selectInput(
              inputId = choice_id, 
              label = "Select a choice", 
              choices = c("Choice 1", "Choice 2", "Choice 3"),
              width = "100%")
            ),
          column(
            width = 6, 
            align = "center",
            if(input$choice_id == "Choice 1"){
              selectizeInput(inputId = "choice_1_options", 
                             label = "Select option from Choice 1:",
                             choices = c("", "Option 1", "Option 2", "Option 3"),
                             options = list(maxItems = 1, placeholder = "Start typing option here...", create = TRUE),
                             width = "100%")

              } else if (input$choice_id == "Choice 2"){
                selectizeInput(inputId = "choice_2_options", 
                               label = "Select option from Choice 2:",
                               choices = c("", "Option 1", "Option 2", "Option 3"),
                               options = list(maxItems = 1, placeholder = "Start typing option here...", create = TRUE),
                               width = "100%")

                } else {
                selectizeInput(inputId = "choice_3_options", 
                               label = "Select option from Choice 3:",
                               choices = c("", "Option 1", "Option 2", "Option 3"),
                               options = list(maxItems = 1, placeholder = "Start typing option here...", create = TRUE),
                               width = "100%")
                  }
            )
          ),
        actionButton(remove_id, "Remove form")
        ),

    observeEvent(input[[remove_id]], {
      removeUI(
        selector = paste0("#", ele_id)
        )
      })
    )

    })
  }

shinyApp(ui = ui, server = server)

Ключевая особенность IПользователь хочет сообщить, что каждая новая форма содержит как selectInput, так и selectizeInput, что он / она может легко удалить всю форму с помощью одной кнопки removeUI и добавить столько форм, сколько ему нужно.

Заранее благодарим вас за исправления, предложения и советы.

...