Collapse and expand row group not working when using .DataTable().clear().destroy();

Collapse and expand row group not working when using .DataTable().clear().destroy();

bbrindzabbrindza Posts: 316Questions: 73Answers: 1

I'm reloading my table using a dropdown with a year selection. The first time in the RowGroup expand and collapse function works. When I reload the table, that functionality is disable. Any thoughts.

The RowGroup expand and collapse function

// Expand/Collaspe Groups
  $('#timeLogTable_OutOfOffice tbody').on('click', 'tr.dtrg-start', function () {
      var pos = $('div.dataTables_scrollBody').scrollTop();
     //console.log(pos)
      var name = $(this).data('name');
      collapsedGroups[name] = !collapsedGroups[name];
      table.draw('page');
  });

The DataTable().clear().destroy(); function

function reloadOutOfOficeTable(){ 

        $("#timeLogTable_OutOfOffice").DataTable().off( 'select deselect');
        $("#timeLogTable_OutOfOffice").DataTable().clear().destroy();

        loadTable()
    }
    

Answers

  • JLegaultJLegault Posts: 31Questions: 6Answers: 2

    Can you get a live.datatable.net version running? I have a few theories but without seeing the loadTable() function I can't say for sure.

    CollapsedGroups is not part of the DataTable, so it does not get cleared by clear() or destroy(). This may mean you have collapsedGroups that are no longer valid, or may not be tied to your table any longer.

    I see you're setting the collapsedGroups[name] to the inverse of what it currently is, because collapsedGroups are remaining this may be setting previously collapsed groups to open, which is not what you would expect.

    You're turning off select and deselect for the reload, I assume you turn them back on and I don't think that is the reason, but like I said without seeing the entire table interacting I can't say for sure.

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Unfortunately I can not provide a live.datatable.net example due to the use of ssp.

    However here is the rest of the HTML and JS

     <div class='row mb-3 ml-1'>
           <label class='mr-2 font-weight-bold'>Year:</label>
           <select class='mr-2' name="yearSelect" id='yearSelect' style='width:4em' onchange='reloadOutOfOficeTable()'></select>
     </div>
     
    <div class='table-responsive tableFont'>
       <table class='table w-100' id='timeLogTable_OutOfOffice'>
          <thead>
             <tr>
              <th></th> 
              <th></th> 
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th>Out Of Office Detail</th>
              <th>Date</th>   
              <th>Total Hours</th>
              <th></th>
            </tr>
           </thead>
       </table>
    </div>
     <div id='tableFooter' class='card-footer small text-muted text-center'></div>
    
    //Used for table group collaspe and exapnd 
    var collapsedGroups = {};
    var level_1 = '';
    var level_2 = '';
    var level_3 = '';
    
    var startYear =2019;
    
    for (i = new Date().getFullYear(); i > startYear; i--)
    {
        $('#yearSelect').append($('<option />').val(i).html(i));
    }
    
    loadTable();
    
    //***************************************************************** 
    // Load Time Log Table 
    //***************************************************************** 
    function loadTable(){ 
    
      var table = $('#timeLogTable_OutOfOffice').DataTable( {
       rowCallback: function(row, data, index){  
                    $(row).find('td:eq(0)').css('width', '200px');
                    $(row).find('td:eq(1)').css('width', '150px');
                    $(row).find('td:eq(2)').css('width', '100px');
                    if(data['time_log_date_yyyymmdd'] <= date && data['out_of_office'] == 'Vacation Day'){
                        $(row).find('td:eq(2)').css('color', 'red');
                        $(row).find('td:eq(3)').css('color', 'red');
                      }
                },
       displayLength:100,
       paging: false,
       dom: 'frtip',
       language: {  sSearch: 'Table Search: '},
       ajax: {
            url: "ssp_TimeLogTable_OutOfOffice.php",
            dataType: 'json',
            data: {employeeNumber: employeeNumber,
                   employeeDepartmentCode: employeeDepartmentCode,
                   selectedYear: $('#yearSelect').val()},
        },
             columns: [
                       { data: 'time_log_year', visible: false},           //0
                       { data: 'employee_last_name', visible: false},      //1
                       { data: 'employee_full_name', visible: false},      //2
                       { data: 'employee_manager_number', visible: false}, //3
                       { data: 'sort_date', visible: false},               //4
                       { data: 'created_by', visible: false},              //5
                       { data: 'created_on', visible: false},              //6
                       { data: 'time_log_date_yyyymmdd', visible: false},  //7
                       {
                         sortable: false,                                  //8  
                           "render": function ( data, type, full, meta ) {
                            if(full.comments == null)   {
                                return '';
                            }else{
                             return '<img class="ui-corner-all" src="../../../images/document-16.ico" alt="'+full.comments+'">';
                            }   
                         }
                       },
                       { data: 'out_of_office', visible: false},                  //9
                       { data: 'out_of_office_reason_detail', orderable: false},  //10
                       { data: 'time_log_date' },                                 //11
                       { data: 'total_hours_formatted', orderable: false},        //12
                       { data: 'total_hours', orderable: false,visible: false}    //13
                      ],
       order: [[0, 'desc'],[2, 'asc'], [9, 'asc'], [1, 'asc'],  [4, 'asc'], ],
       rowGroup: {
                   dataSrc: ['time_log_year', 'employee_full_name', 'out_of_office'],
                   startRender: function (rows, group, level) {
    
                        var totalOutOfOfficeDays = rows
                        .data()
                        .pluck('total_hours')
                        .reduce( function (a, b) {
                        return a + b ;
                   });
    
                  totalOutOfOfficeDays = totalOutOfOfficeDays / 8;
    
                   var all;
    
                       if (level === 0) {
                           level_1 = group;
                           all = group;
                           level_2 ='';
                           level_3 ='';
    
                       } else {
                           // if parent collapsed, nothing to do
                           if (!!collapsedGroups[level-1]) {
                               return;
                           }
    
                         if (level === 1) {
                               level_2 = group;
                          }
    
                         if (level === 2) {
                               level_3 = group;
                          }
    
                         all = level_1 + level_2 +  level_3 + group;
    
                       }
    
                       var collapsed = !!collapsedGroups[all];
    
                       rows.nodes().each(function (r) {
                           r.style.display = 'none';
                           if (collapsed) {
                             r.style.display = '';
                           }});
    
                      //fontawsome + and - 
                      var toggleClass = collapsed ? 'fa fa-minus-circle' : 'fa fa-plus-circle';
                      var groupTD = '';
    
    
                      if(level === 0){
                          groupTD = '<td colspan="' + rows.columns()[0].length +'">' + group + '</td>';
    
                        }else if(level === 1){
                                  groupTD = '<td colspan="' + rows.columns()[0].length +'">' + group + ' (' + totalOutOfOfficeDays + ')</td>';
                        }else{
                                  groupTD = '<td colspan="' + rows.columns()[0].length +'"><span style="color:#007bff"  class="fa fa-fw' + toggleClass + ' toggler"></span>  ' + group + ' (' + totalOutOfOfficeDays + ')</td>';
    
                     }
    
    
                    // Add category name to the <tr>
                    return $('<tr/>')
                      .append(groupTD)
                      .attr('data-name', all)
                      .toggleClass('collapsed', collapsed);
    
                   }
       }
    
     });//END .dataTable
    
    // Expand/Collaspe Groups
      $('#timeLogTable_OutOfOffice tbody').on('click', 'tr.dtrg-start', function () {
          var pos = $('div.dataTables_scrollBody').scrollTop();
          var name = $(this).data('name');
          collapsedGroups[name] = !collapsedGroups[name];
          table.draw('page');
      });
    }
    //***************************************************************** 
    //Reload Time Log Out Of Office Table 
    //***************************************************************** 
        function reloadOutOfOficeTable(){ 
    
            $("#timeLogTable_OutOfOffice").DataTable().off( 'select deselect');
            $("#timeLogTable_OutOfOffice").DataTable().clear().destroy();
    
            loadTable();
        }
    
    
  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    When I reload the table, that functionality is disable.

    Have you verified your click event is being called?

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Yes, it is being called. Tested in console.log

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    You may need to reset the collapsedGroups variable in the reloadOutOfOficeTable() function. Maybe simply using collapsedGroups = {}; will work. If this doesn't help then you will need to trace through the rowGroup.startRender function to understand where the problem is. Or post a link to your page or a test case with an example of your data so we can help debug. We don't need the exact SSP data just need some Javascript data to fill the table. See this Javascript sourced data example.

    Kevin

  • bbrindzabbrindza Posts: 316Questions: 73Answers: 1

    Thanks for the input Kevin, I will let you know how it goes.

  • glimpsed_chaosglimpsed_chaos Posts: 140Questions: 30Answers: 4
    edited May 2021

    It might be because you are destroying the table. In doing so your on click event is no longer associated with the previously created table.

    I don't use destroy. Once I create the table and any events for that table, I only reload my data. After the data is loaded, then I clear the old data, add the new data and draw it to display. This can all be chained like below:

    var data = JSON.parse(fromDBData); //Or ajax, etc...
    var myTable = $('#myTable').DataTable().clear().rows.add(data).draw();
    
    
This discussion has been closed.