aldeed:tabular

v2.1.0Published 7 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

aldeed:tabular

A Meteor package that creates reactive DataTables in an efficient way, allowing you to display the contents of enormous collections without impacting app performance.

Table of Contents

Table of Contents generated with DocToc

ATTENTION: Updating to 2.0

Version 2.0 API is backwards compatible other than the following changes:

  • Requires Meteor 1.3+
  • You must explicitly import the Tabular object into every file where you use it. (import Tabular from 'meteor/aldeed:tabular';)
  • You must configure the Bootstrap theme (or whatever theme you want) yourself. See Installing and Configuring a Theme

This version also includes a few fixes and a few new features.

Features

  • Fast: Uses an intelligent automatic data subscription so that table data is not loaded until it's needed.
  • Reactive: As your collection data changes, so does your table. You can also reactively update the query selector if you provide your own filter buttons outside of the table.
  • Customizable: Anything you can do with the DataTables library is supported, and you can provide your own publish function to build custom tables or tables than join data from two collections.
  • Hot Code Push Ready: Remains on the same data page after a hot code push.

Although this appears similar to the jquery-datatables Meteor package, there are actually many differences:

  • This package is updated to work with Meteor 1.3+.
  • This package has a much smaller codebase and includes less of the DataTables library.
  • This package allows you to specify a Blaze template as a cell's content.
  • This package handles the reactive table updates in a different way.
  • This package is designed to work with any DataTables theme

Installation

$ meteor add aldeed:tabular

Installing and Configuring a Theme

This example is for the Bootstrap theme. You can use another theme package. See https://datatables.net/download/npm

First:

$ npm install --save jquery@1.11.2 datatables.net-bs

Note that we install jquery@1.11.2. This needs to match the current version of jQuery included with Meteor's jquery package. (See the version comment in https://github.com/meteor/meteor/blob/master/packages/jquery/package.js) Otherwise, due to the datatables.net package depending on jquery NPM package, it might automatically install the latest jquery version, which may conflict with Bootstrap or Meteor.

Then, somewhere in your client JavaScript:

1import { $ } from 'meteor/jquery';
2import dataTablesBootstrap from 'datatables.net-bs';
3import 'datatables.net-bs/css/dataTables.bootstrap.css';
4dataTablesBootstrap(window, $);

Online Demo App

View a demonstration project on Meteorpad.

Another example app courtesy of @AnnotatedJS:

Example

Define your table in common code (code that runs in both NodeJS and browser):

1import Tabular from 'meteor/aldeed:tabular';
2import { Template } from 'meteor/templating';
3import moment from 'moment';
4import { Meteor } from 'meteor/meteor';
5import { Books } from './collections/Books';
6
7new Tabular.Table({
8  name: "Books",
9  collection: Books,
10  columns: [
11    {data: "title", title: "Title"},
12    {data: "author", title: "Author"},
13    {data: "copies", title: "Copies Available"},
14    {
15      data: "lastCheckedOut",
16      title: "Last Checkout",
17      render: function (val, type, doc) {
18        if (val instanceof Date) {
19          return moment(val).calendar();
20        } else {
21          return "Never";
22        }
23      }
24    },
25    {data: "summary", title: "Summary"},
26    {
27      tmpl: Meteor.isClient && Template.bookCheckOutCell
28    }
29  ]
30});

And then reference in one of your templates where you want it to appear:

1{{> tabular table=TabularTables.Books class="table table-striped table-bordered table-condensed"}}

The TabularTables.Books helper is automatically added, where "Books" is the name option from your table constructor.

Displaying Only Part of a Collection's Data Set

Add a Mongo-style selector to your tabular component for a table that displays only one part of a collection:

1{{> tabular table=TabularTables.Books selector=selector class="table table-striped table-bordered table-condensed"}}
1Template.myTemplate.helpers({
2  selector() {
3    return {author: "Agatha Christie"}; // this could be pulled from a Session var or something that is reactive
4  }
5});

If you want to limit what is published to the client for security reasons you can provide a selector in the constructor which will be used by the publications. Selectors provided this way will be combined with selectors provided to the template using an AND relationship. Both selectors may query on the same fields if necessary.

1new Tabular.Table({
2  // other properties...
3  selector(userId) {
4    return { documentOwner: userId };
5  }
6});

Passing Options to the DataTable

The DataTables documentation lists a huge variety of available table options and callbacks. You may add any of these to your Tabular.Table constructor options and they will be used as options when constructing the DataTable.

Example:

1new Tabular.Table({
2  // other properties...
3  createdRow( row, data, dataIndex ) {
4    // set row class based on row data
5  }
6});

Template Cells

You might have noticed this column definition in the example:

1{
2  tmpl: Meteor.isClient && Template.bookCheckOutCell
3}

This is not part of the DataTables API. It's a special feature of this package. By passing a Blaze Template object, that template will be rendered in the table cell. You can include a button and/or use helpers and events.

In your template and helpers, this is set to the document for the current row by default. If you need more information in your template context, such as which column it is for a shared template, you can set tmplContext to a function which takes the row data as an argument and returns the context, like this:

1{
2  data: 'title',
3  title: "Title",
4  tmpl: Meteor.isClient && Template.sharedTemplate,
5  tmplContext(rowData) {
6    return {
7      item: rowData,
8      column: 'title'
9    };
10  }
11}

Note: The Meteor.isClient && is there because tables must be defined in common code, which runs on the server and client. But the Template object is not defined in server code, so we need to prevent errors by setting tmpl only on the client.

The tmpl option can be used with or without the data option.

Here's an example of how you might do the bookCheckOutCell template:

HTML:

1<template name="bookCheckOutCell">
2  <button type="button" class="btn btn-xs check-out">Check Out</button>
3</template>

Client JavaScript:

1Template.bookCheckOutCell.events({
2  'click .check-out': function () {
3    addBookToCheckoutCart(this._id);
4  }
5});

Searching

If your table includes the global search/filter field, it will work and will update results in a manner that remains fast even with large collections. By default, all columns are searched if they can be. If you don't want a column to be searched, add the searchable: false option on that column.

When you enter multiple search terms separated by whitespace, they are searched with an OR condition, which matches default DataTables behavior.

If your table has a selector that already limits the results, the search happens within the selector results (i.e., your selector and the search selector are merged with an AND relationship).

Customizing Search Behavior

You can add a search object to your table options to change the default behavior. The defaults are:

1{
2  search: {
3    caseInsensitive: true,
4    smart: true,
5    onEnterOnly: false,
6  }
7}

You can set caseInsensitive or smart to false if you prefer. See http://datatables.net/reference/option/search. The regex option is not yet supported.

onEnterOnly is custom to this package. Set it to true to run search only when the user presses ENTER in the search box, rather than on keyup. This is useful for large collections to avoid slow searching.

There are also two options to optimize searching for particular columns:

1columns: [
2    {
3      data: '_id',
4      title: 'ID',
5      search: {
6        isNumber: true,
7        exact: true,
8      },
9    },
10]

For each column, you can set search.isNumber to true to cast whatever is entered to a Number and search for that, and you can set search.exact to true to search only for an exact match of the search string. (This overrides the table-level caseInsensitive and smart options for this column only.)

Using Collection Helpers

The DataTables library supports calling functions on the row data by appending your data string with (). This can be used along with the dburles:collection-helpers package (or your own collection transform). For example:

Relevant part of your table definition:

1columns: [
2  {data: "fullName()", title: "Full Name"},
3]

A collection helper you've defined in client or common code:

1People.helpers({
2  fullName: function () {
3    return this.firstName + ' ' + this.lastName;
4  }
5});

Note that for this to work properly, you must ensure that the firstName and lastName fields are published. If they're included as the data for other columns, then there is no problem. If not, you can use the extraFields option or your own custom publish function.

Publishing Extra Fields

If your table's templates or helper functions require fields that are not included in the data, you can tell Tabular to publish these fields by including them in the extraFields array option:

1TabularTables.People = new Tabular.Table({
2  // other properties...
3  extraFields: ['firstName', 'lastName']
4});

Modifying the Selector

If your table requires the selector to be modified before it's published, you can modify it with the changeSelector method. This can be useful for modifying what will be returned in a search. It's called only on the server.

1TabularTables.Posts = new Tabular.Table({
2  // other properties...
3  changeSelector(selector, userId) {
4    // modify it here ...
5    return selector;
6  }
7});

Saving state

Should you require the current state of pagination, sorting, search, etc to be saved you can use the default functionality of Datatables.

Add stateSave as a property when defining the Datatable.

1TabularTables.Posts = new Tabular.Table({
2  // other properties...
3  stateSave: true
4});

Add an ID parameter to the template include. This is used in localstorage by datatables to keep the state of your table. Without this state saving will not work.

1{{> tabular table=TabularTables.Posts id="poststableid" selector=selector class="table table-striped table-bordered table-condensed"}}

Security

You can optionally provide an allow and/or allowFields function to control which clients can get the published data. These are used by the built-in publications on the server only.

1TabularTables.Books = new Tabular.Table({
2  // other properties...
3  allow(userId) {
4    return false; // don't allow this person to subscribe to the data
5  },
6  allowFields(userId, fields) {
7    return false; // don't allow this person to subscribe to the data
8  }
9});

Note: Every time the table data changes, you can expect allow to be called 1 or 2 times and allowFields to be called 0 or 1 times. If the table uses your own custom publish function, then allow will be called 1 time and allowFields will never be called.

If you need to be sure that certain fields are never published or if different users can access different fields, use allowFields. Otherwise just use allow.

Caching the Documents

By default, a normal Meteor.subscribe is used for the current page's table data. This subscription is stopped and a new one replaces it whenever you switch pages. This means that if your table shows 10 results per page, your client collection will have 10 documents in it on page 1. When you switch to page 2, your client collection will still have only 10 documents in it, but they will be the next 10.

If you want to override this behavior such that documents displayed in the table remain cached on the client for some time, you can add the meteorhacks:subs-manager package to your app and set the sub option on your Tabular.Table. This can make the table a bit faster and reduce unnecessary subscription traffic, but may not be a good idea if the data is extremely sensitive.

1TabularTables.Books = new Tabular.Table({
2  // other properties...
3  sub: new SubsManager()
4});

Hooks

Currently there is only one hook provided: onUnload

Rendering a responsive table

Use these table options:

1responsive: true,
2autoWidth: false,

Active Datasets

If your table is showing a dataset that changes a lot, it could become unusable due to reactively updating too often. You can throttle how often a table updates with the following table option:

1throttleRefresh: 5000

Set it to the number of milliseconds to wait between updates, even if the data is changing more frequently.

Using a Custom Publish Function

This package takes care of publication and subscription for you using two built-in publications. The first publication determines the list of document _ids that are needed by the table. This is a complex publication and there should be no need to override it. The second publication publishes the actual documents with those _ids.

The most common reason to override the second publication with your own custom one is to publish documents from related collections at the same time.

To tell Tabular to use your custom publish function, pass the publication name as the pub option. Your function:

  • MUST accept and check three arguments: tableName, ids, and fields
  • MUST publish all the documents where _id is in the ids array.
  • MUST do any necessary security checks
  • SHOULD publish only the fields listed in the fields object, if one is provided.
  • MAY also publish other data necessary for your table

Example

Suppose we want a table of feedback submitted by users, which is stored in an AppFeedback collection, but we also want to display the email address of the user in the table. We'll use a custom publish function along with the reywood:publish-composite package to do this. Also, we'll limit it to admins.

server/publish.js

1Meteor.publishComposite("tabular_AppFeedback", function (tableName, ids, fields) {
2  check(tableName, String);
3  check(ids, Array);
4  check(fields, Match.Optional(Object));
5
6  this.unblock(); // requires meteorhacks:unblock package
7
8  return {
9    find: function () {
10      this.unblock(); // requires meteorhacks:unblock package
11
12      // check for admin role with alanning:roles package
13      if (!Roles.userIsInRole(this.userId, 'admin')) {
14        return [];
15      }
16
17      return AppFeedback.find({_id: {$in: ids}}, {fields: fields});
18    },
19    children: [
20      {
21        find: function(feedback) {
22          this.unblock(); // requires meteorhacks:unblock package
23          // Publish the related user
24          return Meteor.users.find({_id: feedback.userId}, {limit: 1, fields: {emails: 1}, sort: {_id: 1}});
25        }
26      }
27    ]
28  };
29});

common/helpers.js

1// Define an email helper on AppFeedback documents using dburles:collection-helpers package.
2// We'll reference this in our table columns with "email()"
3AppFeedback.helpers({
4  email() {
5    var user = Meteor.users.findOne({_id: this.userId});
6    return user && user.emails[0].address;
7  }
8});

common/tables.js

1TabularTables.AppFeedback = new Tabular.Table({
2  name: "AppFeedback",
3  collection: AppFeedback,
4  pub: "tabular_AppFeedback",
5  allow(userId) {
6    // check for admin role with alanning:roles package
7    return Roles.userIsInRole(userId, 'admin');
8  },
9  order: [[0, "desc"]],
10  columns: [
11    {data: "date", title: "Date"},
12    {data: "email()", title: "Email"},
13    {data: "feedback", title: "Feedback"},
14    {
15      tmpl: Meteor.isClient && Template.appFeedbackCellDelete
16    }
17  ]
18});

Tips

Some useful tips

Get the DataTable instance

1var dt = $(theTableElement).DataTable();

Detect row clicks and get row data

1Template.myTemplate.events({
2  'click tbody > tr': function (event) {
3    var dataTable = $(event.target).closest('table').DataTable();
4    var rowData = dataTable.row(event.currentTarget).data();
5    if (!rowData) return; // Won't be data if a placeholder row is clicked
6    // Your click handler logic here
7  }
8});

Search in one column

1var dt = $(theTableElement).DataTable();
2var indexOfColumnToSearch = 0;
3dt.column(indexOfColumnToSearch).search('search terms').draw();

Adjust column widths

By default, the DataTables library uses automatic column width calculations. If this makes some of your columns look squished, try setting the autoWidth: false option.

Turning Off Paging or Showing "All"

When using no paging or an "All" (-1) option in the page limit list, it is best to also add a hard limit in your table options like limit: 500, unless you know the collection will always be very small.

Customize the "Processing" Message

To customize the "Processing" message appearance, use CSS selector div.dataTables_wrapper div.dataTables_processing. To change or translate the text, see https://datatables.net/reference/option/language.processing

I18N Example

Before rendering the table on the client:

1if (Meteor.isClient) {
2	$.extend(true, $.fn.dataTable.defaults, {
3		language: {
4      "lengthMenu": i18n("tableDef.lengthMenu"),
5      "zeroRecords": i18n("tableDef.zeroRecords"),
6      "info": i18n("tableDef.info"),
7      "infoEmpty": i18n("tableDef.infoEmpty"),
8      "infoFiltered": i18n("tableDef.infoFiltered")
9    }
10	});
11}

More options to translate can be found here: https://datatables.net/reference/option/language

Reactive Column Titles

You can set the titleFn column option to a function instead of supplying a string title option. This is reactively rerun as necessary.

Optimizing the Total Table Count

By default, a count of the entire available filtered dataset is done on the server. This can be slow for large datasets. You have two options that can help:

First, you can calculate total counts yourself and return them from a function provided as the alternativeCount option to your Tabular.Table:

1alternativeCount: (selector) => 200,

Second, you can skip the count altogether. If you do this, we return a fake count that ensures the Next button will be available. But the fake count will not be the correct total count, so the paging info and the numbered page buttons will be misleading. To deal with this, you should use pagingType: 'simple' and either info: false or an infoCallback function that omits the total count:

1skipCount: true,
2pagingType: 'simple',
3infoCallback: (settings, start, end) => `Showing ${start} to ${end}`,

Integrating DataTables Extensions

There are a wide variety of useful extensions for DataTables. To integrate them into Tabular, it is best to use the NPM packages.

Example: Adding Buttons

To add buttons for print, column visibility, file export, and more, you can use the DataTables buttons extension. Install the necessary packages in your app with NPM. For example, if you're using the Bootstrap theme, run:

$ npm install --save datatables.net-buttons datatables.net-buttons-bs

For package names for other themes, see https://datatables.net/download/npm

Once the packages are installed, you need to import them in one of your client JavaScript files:

1import { $ } from 'meteor/jquery';
2
3// Bootstrap Theme
4import dataTablesBootstrap from 'datatables.net-bs';
5import 'datatables.net-bs/css/dataTables.bootstrap.css';
6
7// Buttons Core
8import dataTableButtons from 'datatables.net-buttons-bs';
9
10// Import whichever buttons you are using
11import columnVisibilityButton from 'datatables.net-buttons/js/buttons.colVis.js';
12import html5ExportButtons from 'datatables.net-buttons/js/buttons.html5.js';
13import flashExportButtons from 'datatables.net-buttons/js/buttons.flash.js';
14import printButton from 'datatables.net-buttons/js/buttons.print.js';
15
16// Then initialize everything you imported
17dataTablesBootstrap(window, $);
18dataTableButtons(window, $);
19columnVisibilityButton(window, $);
20html5ExportButtons(window, $);
21flashExportButtons(window, $);
22printButton(window, $);

Finally, for the Tabular tables that need them, add the buttons and buttonContainer options. The buttons option is part of DataTables and is documented here: https://datatables.net/extensions/buttons/ The buttonContainer option is part of aldeed:tabular and does the tricky task of appending the buttons to some element in the generated table. Set it to the CSS selector for the container.

Bootstrap example:

1new Tabular.Table({
2  // other properties...
3  buttonContainer: '.col-sm-6:eq(0)',
4  buttons: ['copy', 'excel', 'csv', 'colvis'],
5});

If you are using the default DataTables theme, you can use the dom option instead of buttonContainer. See https://datatables.net/extensions/buttons/#Displaying-the-buttons