Mark
Mark

Reputation: 2899

How to avoid mixup between rowcallback and sorting in datatable

With the help of a previous question, I can now style selected rows (intended for the user to select rows to be excluded from further analysis), but I have found out that sorting the datatable after executing the functionality to exclude rows (gray them out and add a different icon, keeps the icon in the correct row, but grays out the wrong rows.

here is the table after deselecting rows 2,3 and 4 before sorting: enter image description here

and after sort: (with the crosses at the right rows, but the graying out not.

enter image description here

   library(shiny)
      library(DT)

  mtcars <- as.data.table(mtcars[1:15, )
  ui <- fluidPage(
    # actionButton('SubmitRemoval', 'Exclude selected rows'),
    # actionButton('UndoRemoval', 'Include full data'),
    # br(),
    DTOutput('metadataTable')

  )

  server <- function(input, output,session) {

    values <- reactiveValues()

    rowCallbackMeta = function(rows){
      c(
        "function(row, data, num, index){",
        sprintf("  var rows = [%s];", paste0(rows-1, collapse = ",")),
        "  if(rows.indexOf(num) > -1){",
        "    for(var i=0; i<data.length; i++){",
        "      $('td:eq('+i+')', row)",
        "        .css({'color': 'rgb(211,211,211)', 'font-style': 'italic'});",
        "    }",
        "  }",
        "    $('td:eq(3)', row).html(data[3].toExponential(2));",
        "}"  
      )
    }
    output$metadataTable <-  DT::renderDataTable({

      rows <- values$RowsRemove

      # mtcars1 <- cbind(Selected ='<span style = "color:#31C769 ; font-size:18px"><i class="fa fa-check"></i></span>', mtcars)
      mtcars1 <- cbind(Selected ='<span style = "color:red ; font-size:18px"><i class="glyphicon glyphicon-ok"></i></span>', mtcars)

      print(rows)
      # if(!is.null(rows)) { 
      mtcars1$Selected[rows] <- '<span style = "color:red ; font-size:18px"><i class="glyphicon glyphicon-remove"></i></span>' 
      # }

      Table_opts <- list(
        dom = 'frtipB',
        searching = F,
        pageLength = 50,
        searchHighlight = TRUE,
        colReorder = TRUE,
        fixedHeader = TRUE,
        buttons = list('copy', 'csv',
                       list(
                         extend = "collection",
                         text = 'Deselect', 
                         action = DT::JS("function ( e, dt, node, config ) {
                                       Shiny.setInputValue('SubmitRemoval', true, {priority: 'event'});
                                     }")
                       ),
                       list(
                         extend = "collection",
                         text = 'Restore', 
                         action = DT::JS("function ( e, dt, node, config ) {
                                       Shiny.setInputValue('UndoRemoval', true, {priority: 'event'});
                                     }")
                       )
        ),
        paging    = TRUE,
        deferRender = TRUE,
        columnDefs = list(list(className = 'dt-right', targets = '_all')),
        rowCallback = JS(rowCallbackMeta(rows)),
        scrollX = T,
        scrollY = 440
      )
      DT::datatable(mtcars1, 
                    escape = FALSE, 
                    extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                    selection = c('multiple'),
                    rownames = FALSE
                    ,
                    options = Table_opts
      )
    })


    observeEvent(values$RowsRemove, {
      print('seeing rows remove')
      values$Datafiles_meta_Selected  <-  values$Datafiles_meta_Selected[-c(values$RowsRemove),]
    })

    observeEvent(input[['SubmitRemoval']], { 
      if(is.null(values$RowsRemove)) { values$RowsRemove <- as.numeric()}
      values$RowsRemove <- unique(c(values$RowsRemove, input[["metadataTable_rows_selected"]]))
    })

    observeEvent(input[["UndoRemoval"]], { 
      values$RowsRemove <- NULL
      values$Datafiles_meta_Selected <- values$Datafiles_meta
    })

  }

  shinyApp(ui, server)

Upvotes: 5

Views: 457

Answers (1)

NicE
NicE

Reputation: 21443

The num you are using in your javascript to select rows to gray out is based on the row number on the current display so not impacted by sorting.

You could try replacing your if statement in your rowCallbackMeta function by:

if(data[0].search('remove') > -1)

This looks for "remove" in the first column of the data to exclude rows, and works because your glyphicon in the first column is updated to <i class="glyphicon glyphicon-remove"></i> when you exclude rows.

Upvotes: 2

Related Questions