闪亮的数据表:禁用某些行的行选择 [英] Shiny DataTable: Disable row selection for certain rows

查看:67
本文介绍了闪亮的数据表:禁用某些行的行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定 Shiny DataTable 是否有可能禁用某些行的行选择。

I am trying to determine if it is possible for a shiny DataTable to have row selection disabled for certain rows.

使用 DT :: datatable 选择参数>我可以预选行,确定用户是选择行还是选择列,还是全部选择,然后完全禁用选择,但是我不清楚是否可以指出要排除的特定行。

Using the selection parameter of DT::datatable I can pre-select rows, determine whether the user selects rows or columns or both, and disable selection entirely, but it isn't clear to me if I can indicate specific rows to exclude. Is this possible?

问候

推荐答案

使用选择扩展名即可:

library(DT)
library(shiny)

dat <- iris[1:17,]

rowCallback <- c(
  "function(row, data, displayNum, displayIndex){",
  "  var indices = [0, 2, 4, 15];",
  "  if(indices.indexOf(displayIndex) > -1){",
  "    $(row).find('td').addClass('notselectable');",
  "  }",
  "}"
)

shinyApp(
  ui = fluidPage(
    DTOutput("table")
  ),
  server = function(input, output, session) {    
    output[["table"]] <- renderDT({
      dat %>%
        datatable(options = list(
          rowCallback = JS(rowCallback), 
          select = list(style = "multi", selector = "td:not(.notselectable)")
        ), 
        extensions = "Select", selection = "none"
        )
    }, server = FALSE)
  }
)

但是如果您需要<$ c $中选定行的索引c> input $ table_rows_selected ,您必须为此编写JavaScript代码:

But if you need the indices of the selected rows in input$table_rows_selected, you have to code in JavaScript for that:

callback <- c(
  "var id = $(table.table().node()).closest('.datatables').attr('id');",
  "table.on('click', 'tbody', function(){",
  "  setTimeout(function(){",
  "    var indexes = table.rows({selected:true}).indexes();",
  "    var indices = Array(indexes.length);",
  "    for(var i = 0; i < indices.length; ++i){",
  "      indices[i] = indexes[i];",
  "    }",
  "    Shiny.setInputValue(id + '_rows_selected', indices);",
  "  }, 0);",
  "});"
)

shinyApp(
  ui = fluidPage(
    DTOutput("table")
  ),
  server = function(input, output, session) {    
    output[["table"]] <- renderDT({
      dat %>%
        datatable(
          callback = JS(callback),
          options = list(
            rowCallback = JS(rowCallback), 
            select = list(style = "multi", selector = "td:not(.notselectable)")
          ), 
          extensions = "Select", selection = "none"
        )
    }, server = FALSE)
    observe({
      print(input[["table_rows_selected"]])
    })
  }
)

这篇关于闪亮的数据表:禁用某些行的行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆