2

Example use case:

When viewing a Contact, on the Relationships tab we'd like the DataTables to default to showing 50 records.

1 Answer 1

2

You can alter any DataTable table through it's API as long as you are in Civi's jQuery context (CRM.$)

You could use hook_civicrm_alterTemplateFile or hook_civicrm_buildForm for example to load your script:

Civi::resources()->addScriptFile( 'my-extension', 'js/alterDataTables.js' );

Then in your js:

// alterDataTables.js file
CRM.$( function( $ ) {
  // get and itarate over all dataTables
  $( '.dataTable' ).map( function( index, table ) {
    // get dataTable instance
    $( table ).DataTable()
      // set page length
      .page.len( 2 )
      // draw table
      .draw()
  } );
} );

The above example was given to me so may have worked in some places e.g. when the dataTable is available on page load. For my use-case I needed to work with the 'Relationships' tab tables when viewing a Contact. In this case, $('.dataTable') would select nothing unless I responded to the ajax event, in which case I also needed to add once() to avoid an infinite loop of redrawing tables:

CRM.$(function($) {
  $(document).ajaxComplete(function() {
    var dt = $('.dataTable');
    if (dt.length) {
      $('.dataTable').once().map(function(index, table) {
        // get dataTable instance
        $(table).once().DataTable()
          // set page length
          .page.len(50)
          // draw table
          .draw()
      });
    }
  }); 
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.