使用selectInput更新数据表并插入数据库

时间:2019-04-05 22:51:13

标签: r mongodb shiny

尝试在表单中使用selectInput

  • 选择是从mongodB的集合中获取的。
  • 当用户 完成表单并提交(将其插入另一个集合 (在mongo中),selectInput中的数据未捕获。
  • 试图使其成为reactive或在服务器中使用observeEvent /updateSelectInput,但无法使其正常工作。

这是完整的代码:

library(shiny)
library(mongolite)
library(jsonlite)

# which fields get saved 
fieldsAll <- c("Name", "selectOne", "tags")

saveData <- function(data) {
  # Connect to the database
}

# load all responses into a data.frame
loadData <- function() {
  # Connect to the database
}

fetchData <- function() {
  # Connect to the database
}

shinyApp(
  ui = tagList(
    navbarPage(
      tabPanel("Technology",
               sidebarPanel(
                 textInput("Name",label ='Name:'),
                 selectInput('selectOne',
                             label ='Select One:',
                             choices=head(fetchData()),
                             selected = "",
                             multiple = FALSE),
                 selectizeInput("tags", "Tags:", NULL, multiple = TRUE, options=list(create=TRUE)),
                 actionButton("submit", "Submit", class = "btn-primary")
               ),
               mainPanel(
                 tabsetPanel(
                   tabPanel("Table",
                            uiOutput("adminPanelContainer")
                   )
                 )
               )
      )
    )
  ),
server = function(input, output, session) {

formData <- reactive({
  fieldsAll 
  data <- sapply(fieldsAll, function(x) input[[x]])
  data <- t(data)
  data 
})    

observeEvent(input$submit, {
  saveData(formData())
  },
)

# render the admin panel
output$adminPanelContainer <- renderUI({
    DT::dataTableOutput("responsesTable")
})

# Update the responses table whenever a new submission is made
responses_data <- reactive({
  input$submit
  data <- loadData()
  data
})

# Show the responses in the admin table
output$responsesTable <- DT::renderDataTable({
  DT::datatable(
    responses_data(),
    rownames = FALSE,
    options = list(searching = TRUE, lengthChange = FALSE)
  )
})
}
)

1 个答案:

答案 0 :(得分:0)

在df中添加具有选定值的列是可行的:

formData <- reactive({
 fieldsAll 
 data <- sapply(fieldsAll, function(x) input[[x]])
 data <- c(data,selectOne= input$selectOne)        #added line   
 data <- t(data)
 data 
})