Example use case:
When viewing a Contact, on the Relationships tab we'd like the DataTables to default to showing 50 records.
CiviCRM Stack Exchange is a question and answer site for administrators and users of the CiviCRM Constituent Relationship Management software. It only takes a minute to sign up.
Sign up to join this communityYou 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()
});
}
});
});