【发布时间】:2022-08-03 00:57:21
【问题描述】:
我有一个闪亮的模块,它显示一个带有注释列的表,用户可以在其中输入文本在客户端,然后将 cmets 存储在数据库中。 现在,我想添加另一个带有复选框的列,并将其对应的值(TRUE/FALSE)存储在数据库中。不确定如何从表中检索复选框值。以下是我对示例数据的尝试。
library(tidyverse)
library(shinyWidgets)
library(shiny)
library(htmlwidgets)
mtcars_df <- mtcars %>%
rownames_to_column(var=\"car\")
writeback_UI <- function (id) {
ns <- NS(id)
DT::dataTableOutput(ns(\'records_tbl\'))
}
shinyInput = function(FUN, len, id, ...) {
inputs = character(len)
for (i in seq_len(len)) {
inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
}
inputs
}
# obtain the values of inputs
shinyValue = function(id, len) {
unlist(lapply(seq_len(len), function(i) {
value = input[[paste0(id, i)]]
if (is.null(value)) NA else value
}))
}
writeback_server <- function (id,records_data) {
#stopifnot(is.reactive(records_data))
shiny::moduleServer(id, function (input,output,session) {
#initiate a reactive variable for storing comments
comments_df <- reactiveVal(tibble(car=rownames(mtcars),comments=NA_character_))
records_df <- reactive({
records_data %>%
left_join(comments_df()) %>%
mutate(key_check= shinyInput(checkboxInput,nrow(.), \'cb_\', value = TRUE))
#mutate(check_values=shinyValue(\'cb_\', nrow(.)))
})
output$records_tbl <- DT::renderDT({
num_cols <- dim(records_df())[2]-2
DT::datatable(
records_df(),
editable = list(target=\"column\",disable=list(columns= 1:num_cols)),
filter = \"top\",
escape = FALSE,
selection = \'none\',
options = list(
dom = \'t\',
paging = TRUE,
ordering = FALSE,
preDrawCallback = JS(\'function() { Shiny.unbindAll(this.api().table().node()); }\'),
drawCallback = JS(\'function() { Shiny.bindAll(this.api().table().node()); } \'),
pageLength = 10,
scrollX=TRUE,
buttons=c(\'copy\',\'csv\',\'excel\')),
)
}
)
observe({
req(input$records_tbl_cell_edit)
comments_data <- records_df() %>%
slice(input$records_tbl_cell_edit$row) %>%
select(car) %>%
mutate(comment=input$records_tbl_cell_edit$value) %>%
filter(comment!=\"\")
comments_df(comments_df() %>%
rows_upsert(comments_data) %>%
distinct())
}) %>%
bindEvent(input$records_tbl_cell_edit)
return(
reactive({records_data %>%
left_join(comments_df())
}))
#
}
)
}
WriteBackTestApp <- function() {
mtcars_df <- mtcars %>% rownames_to_column(var = \"car\")
ui <- fluidPage(
writeback_UI(\"wb\")
)
server <- function(input, output, session) {
writeback_server(\"wb\",mtcars_df)
}
shinyApp(ui, server)
}
WriteBackTestApp()
标签: r checkbox shiny dt shinymodules