有条件地将 Shiny 按钮禁用为 Handsontable 格式

Disable Shiny button conditionnaly to a rHandsontable format

我在 Shiny 应用程序中有一个 rhandsontable,它具有一些条件格式,例如如果特定列上缺少数据(例如下面的 col1),则将整行渲染为红色。

现在,我还想 return 将此信息(缺少强制值)发送给 Shiny(例如使用布尔值),以便采取其他操作(例如禁用闪亮按钮).

有没有一种简单的方法可以做到这一点,或者我是否应该在 rhandsontable 上并行编写观察者代码并再次测试是否填充了必填列?

这是我想要实现的示例:

library(shiny)
library(rhandsontable)

DF <- data.frame(col1 = c(1, NA, 3), col2 = c(letters[23:22], NA), col3 = round(rnorm(3, 1e6, 1e3),0))

server <- shinyServer(function(input, output, session) {
  
  output$rt <- renderRHandsontable({
    rhandsontable(DF) %>%
      hot_cols(renderer = "
           function (instance, td, row, col, prop, value, cellProperties) {
             Handsontable.renderers.NumericRenderer.apply(this, arguments);
             var col_col1 = instance.getData()[row][0]
              if(!col_col1) {
                td.style.background = 'pink';
              }
           }")
  })
})

ui <- shinyUI(fluidPage(
  rHandsontableOutput("rt"),
  br(),
  actionButton(inputId = "btn1",
             label = "disable this btn when at least one cell is red")
))

shinyApp(ui, server)

这是一个方法。

library(shiny)
library(rhandsontable)
library(shinyjs)

DF <- data.frame(
  col1 = c(1, NA, 3), 
  col2 = c(letters[23:22], NA), 
  col3 = round(rnorm(3, 1e6, 1e3),0),
  col4 = 3:1
)

server <- shinyServer(function(input, output, session) {
  
  session$sendCustomMessage("dims", list(nrows = nrow(DF), ncols = ncol(DF)))
  
  output$rt <- renderRHandsontable({
    rhandsontable(DF) %>%
      hot_cols(renderer = "
           function (instance, td, row, col, prop, value, cellProperties) {
             Handsontable.renderers.NumericRenderer.apply(this, arguments);
             if(!value) {
               td.style.background = 'pink';
               array[col][row] = true;
             } else {
               array[col][row] = false;
             }
             Shiny.setInputValue('missingValues:shiny.matrix', array);
           }")
  })
  
  observeEvent(input[["missingValues"]], {
    if(any(input[["missingValues"]])){
      disable("btn1")
    }else{
      enable("btn1")
    }
  })
  
  observe({
    print(input$missingValues)
  })
})

js <- HTML(
  "var array = [];",
  "function initializeArray(dims){",
  "  for(var i = 0; i < dims.ncols; ++i){",
  "    array.push(new Array(dims.nrows));",
  "  }",
  "}",
  "$(document).on('shiny:connected', function(){",
  "  Shiny.addCustomMessageHandler('dims', initializeArray);",
  "});"
)

ui <- shinyUI(fluidPage(
  tags$head(tags$script(js)), 
  useShinyjs(),
  rHandsontableOutput("rt"),
  br(),
  actionButton(inputId = "btn1",
               label = "disable this btn when at least one cell is red")
))

shinyApp(ui, server)