Child Tables

The Live Data example demonstrated how you can use another table for links. There the three related tables (Employee, Offices and Positions) are shown separately and can be edited independently of each other.

This example takes that a little further, and uses the Offices table (the parent) as a filter for the Employee table (the child). Initially, the Employee table isn't shown, but clicking on the Office table then shows all employees using that office. Both tables are fully editable, and new entries can be added to both.

Offices

This example was achieved by adding the following code into the document:

// The Offices table
var parent = {
  table: null,
  editor: null,
  id: 'ct-ea89b954-4e00-11ec-a399-c37d080c8b30',
  selected: null
};
// The Person table
var child = {
  table: null,
  editor: null,
  id: 'ct-2efd2e3c-4e00-11ec-a93d-b34dba1f0acd'
};

var linkId = 'l-5';

function start() {
  $.fn.dataTable.ext.search.push(
    function( settings, searchData, index, rowData, counter ) {
      // Only filter on the child table
      if (settings.nTable.id !== child.id) {
        return true;
      }

      // If no office selected, hide all rows
      if (! parent.selected) {
        return false;
      }

      // If there is an office selected, filter to just rows with that office
      return rowData[linkId].map(l => l.id).includes(parent.selected);
    }
  );

  parent.table
  .on('select', function () {
    // Get the id of the selected office
    let row = parent.table.row({selected: true}).data();
    parent.selected = row.id.split('-')[1] * 1; // get the id integer

    // Display the child table
    $('#' + child.id).closest('.cloudtables').css('display', 'block');
    child.table.draw();

    // Set the default for new rows in the child to match the selected parent row
    child.editor.field(linkId + '[].id').def(parent.selected);
  })
  .on('deselect', function () {
    // Hide child table on deselect
    $('#' + child.id).closest('.cloudtables').css('display', 'none');
  });
}

document.addEventListener('ct-ready', function(e) {
  // Make a note of which table is which
  $('#' + child.id).closest('.cloudtables').css('display', 'none');
  if (e.table.table().node().id === parent.id) {
    parent.table = e.table;
    parent.editor = e.editor;

    e.table.select.style('single');
  }
  else if (e.table.table().node().id === child.id) {
    child.table = e.table;
    child.editor = e.editor;
  }

  // Wait for both tables to become ready
  if (parent.table && child.table) {
    start();
  }
});

Other examples