首页 > 解决方案 > 向 Shiny DT 添加按钮以拉起模态

问题描述

我正在尝试在我的数据表中添加一列按钮,单击该按钮会弹出一个模式,但是我无法使用我在此处此处在线找到的示例。

我的一些要求:

代码:

library(shiny)
library(shinydashboard)
library(DT)

ui = dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    DTOutput('x1'),
    verbatimTextOutput("test")
    )
    )

server = function(input, output) {

  ##DATA TABLE WHERE I NEED A BUTTON##

  output$x1 = renderDT(
    iris,
    selection = 'single',
    options = list(
    )
  )

  ##MODAL CALLED BASED ON BUTTON CLICK

  observeEvent(input$x1_cell_clicked, {

    row = input$x1_cell_clicked$row

    if (is.null(row) || row == '') {} else{

      showModal(modalDialog(
        title = paste0("Timeline!",row),
        size = "s",
        easyClose = TRUE,
        footer = NULL
      ))
    }

  })

  output$test <- renderPrint({
    input$x1_cell_clicked$row
  })

}

shinyApp(ui, server)

标签: rshinydt

解决方案


在您的评论中,您询问了多个数据表的情况。是你想要的吗?

library(shiny)
library(DT)

button <- function(tbl){
  function(i){
    sprintf(
      '<button id="button_%s_%d" type="button" onclick="%s">Click me</button>', 
      tbl, i, "Shiny.setInputValue('button', this.id);")
  }
}

dat1 <- cbind(iris, 
              button = sapply(1:nrow(iris), button("tbl1")), 
              stringsAsFactors = FALSE)
dat2 <- cbind(mtcars, 
              button = sapply(1:nrow(mtcars), button("tbl2")), 
              stringsAsFactors = FALSE)

ui <- fluidPage(
  fluidRow(
    column(
      width = 6,
      DTOutput("tbl1", height = "500px")
    ),
    column(
      width = 6,
      DTOutput("tbl2", height = "500px")
    )
  )

)

server <- function(input, output){

  output[["tbl1"]] <- renderDT({
    datatable(dat1, escape = ncol(dat1)-1, fillContainer = TRUE)
  })

  output[["tbl2"]] <- renderDT({
    datatable(dat2, escape = ncol(dat2)-1, fillContainer = TRUE)
  })

  observeEvent(input[["button"]], {
    splitID <- strsplit(input[["button"]], "_")[[1]]
    tbl <- splitID[2]
    row <- splitID[3]
    showModal(modalDialog(
      title = paste0("Row ", row, " of table ", tbl, " clicked"),
      size = "s",
      easyClose = TRUE,
      footer = NULL
    ))
  })
}

shinyApp(ui, server)

在此处输入图像描述


推荐阅读