簡體   English   中英

閃亮的模塊:如何使用 DT::datatables 訪問 selected_rows?

[英]Shiny modules: how to access selected_rows with DT::datatables?

使用閃亮模塊和 DT::datatable 時,我想訪問 selected_rows 服務器端。 如果我的 DT:datatable ID 是my_DT_table那么我希望對象input$my_DT_table_selected_rows包含所選行的索引。 這在沒有模塊的閃亮應用程序中非常有效。

但是,如果我使用模塊,那么這種方法就不再有效,輸入對象input$my_DT_table_selected_rows不再包含所選行的索引。

使用 DT:datatable 函數時,我們可以使用內置功能來了解 UI 中的選定行。

對象: input$my_DT_table_rows_selected包含所選行的索引,其中my_DT_table是 DT::datatable 的 ID。

但是,在使用模塊時,表的名稱現在不同了。 它有一個前綴,等於用於調用模塊的 UI 函數的 ID。 因此,如果該 ID 是my_ID ,則表名將變為: my_ID-table_name (注意 ID 后面的連字符)。 這可以使用瀏覽器中的開發人員工具輕松驗證(例如 FireFox 中的檢查器)。 然后關聯的輸入對象名稱變為(我們需要反引號以防止 R 將連字符解釋為減號):

input$`my_ID-table_name_rows_selected`

這是一個非常基本的示例,其中包含一些關於如何將反應對象傳遞給模塊的額外學習。 反應對象包含所選行的索引。 我需要不帶括號地傳遞它。 在 module_server 函數內部,我用括號引用反應對象。

ui_module.R 中的UI 模塊

module_ui <- function(id) {
  ns <- NS(id) # create namespace

  tagList(
    fluidRow(column(6, DT::dataTableOutput(ns("dt_table")))),
    fluidRow(column(4, verbatimTextOutput(ns("render_selected_line"))))
  )
}

server_module.R 中的服務器模塊

table_server <- function(input, output, session, data) {

  output$dt_table <- DT::renderDataTable(
    DT::datatable(
    data = data,
    selection = "single"
    )
  )
}

selected_line_server <- function(input, output, session, data) { 
  output$render_selected_line <- renderText({
    paste0("My selection was: ", data()) # refer to the reactive object with parenthesis
  })

}

閃亮的應用

library(shiny)
library(dplyr)
library(DT)

source("./modules/ui_module.R")
source("./modules/server_module.R")

ui <- fluidPage(
  module_ui("my_ID")
)

server = function(input, output, session) {
  data <- mtcars
  callModule(table_server, id = "my_ID", data = data) # data is not reactive
  callModule(selected_line_server, id = "my_ID", data = selectedLine) # refer to the reactive object selectedLine without parenthesis

  selectedLine <- reactive({
    req(input$`my_ID-dt_table_rows_selected`)
    if (is.null(input$`my_ID-dt_table_rows_selected`)) {
      return(NULL)
    } else {
      rows_selected <- as.numeric(input$`my_ID-dt_table_rows_selected`) # we need to prefix dt_table_rows_selected with the ID of the UI function "my_ID" and a hyphen
    }
  })

}

shinyApp(ui = ui, server = server)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM