DataTables in Visualforce, part 1

I’ve been doing a lot of work with jQuery DataTables. They can add a nice custom interface for your Salesforce data with very little coding. I’m going to devote the next few posts on ways to use DataTables in your Visualforce pages. In this first post, we’ll make it pretty simple using a standard html table created using an <apex:repeat> tag and then using jQuery to make the table into a DataTable with zero configuration. Then we’ll do a couple of extra things to make our table a little more functional.

First, we need a controller that gives us the data we need. Our example will be listing contacts in Salesforce.

Now, here is a Visualforce page that turns that ugly table into a nice looking DataTable with sorting and filtering, plus some styling. Pretty easy, right?

Alright, let’s get a little fancy. We want to have a drop down listing all the accounts so we can filter by account name. We also want to default the order of the rows by contact last name. To do the sorting, we specify order with an array. The columns are zero-based, so last name which is the 3rd column will be index 2.

To add the drop down, we use jQuery to get the unique values from the first column, sort them and then append them to a select component on the page. We also add a handler to the select component to filter when the value changes. If “All” is selected, then it clears the filter.

And here’s what it looks like.datatables1

In the next post, I’ll show how to leverage Visualforce remoting to add some dynamic features to a DataTable.

 

7 thoughts on “DataTables in Visualforce, part 1”

  1. Thanks for sharing – datatables is simply awesome tool!

    I’d be careful thought including JavaScript files from remote sources. Even if a public CDN like the one provided by jQuery or DataTable may sound reliable, if they get hacked by any individual, this could put your Salesforce users at serious risk when viewing the VF pages (like injecting some nasty JS). I suggest updating with Static Resources usage :)!

    Otherwise, gj!

    1. Good point. I find it easier to demonstrate using public CDN as there’s less to setup. Once you get to production, static resources are definitely a good idea.

Leave a Reply