Building a jQuery DataTables Plugin

I like datatables and use it a lot at work. I’ve used datatables so much that I’ve written a CakePHP plugin for it, creatively named CakePHP-Datatables. Documentation on creating plugins is a little rough though. It took me quite some time to write my first one, so I decided to give a little back, and take you through creating a very simple plugin called, My Button. This plugin will add a button to your datatables instance.

Getting Started

Your first step is to familiarize yourself with some of the DataTables documentation on creating plugins. Now that you’ve done that we’ll break down how DataTables supports plugins. Your plugin source must be loaded after the datatables source has been loaded. Next your plugin code will access the DataTables global exposed through jQuery and “announce your plugin”. This is done by assigning an sDom attribute and calling one of DataTables callback methods. Here’s your starting code.

You can load this into an existing DataTables of  yours by appending “X” to your sDom attribute.

Adding a Button

Adding the button is straight foward. We need to create an object for our plugin and then replace our hello world alert with an instance of the object. That object will do everything we need for our plugin.

So here we created an object called DT_MyButton and then passed oDTSettings as an argument. oDTSettings contains all of the settings and additional methods for our instance of DataTables. In our object we push our code into DataTables aoInitComplete callback. When the table is created and data is loaded, aoInitComplete gets called. We then get our table wrapper element from oDTSettings.nTableWrapper and use that to append our button. Now lets load in our plugin.

Passing Settings into our Plugin

You may want to pass settings into your plugin which would allow developers to change the value of the button or the alert message. Doing this requires a few changes to our code.

Now our datatables code becomes this:

You can do a lot more with the new beta version of dataTables as it exposes a lot of great stuff in a revamped API. Using the new API and a more complex version of the My Button plugin I was able to collect various information the user had entered in filters, send this data back to the server, and render PDF and Excel files for download.

Everyone knows that debugging is twice as hard as writing a program in the first place. So if you are as clever as you can be when you write it, how will you ever debug it?

– Brian Kernighan, Computer Scientist at Bell Labs, Co-creator of Unix