Sunday, 24 May 2015

DataTables in Visualforce Part 1

Introduction

One day a client asked us to display the Opportunities of an Account. We thought a nice Visualforce PageBlockTable would do the job. Then the client added functionalities like:

  • Pagination (as there would be around 100 records),
  • Sorting of columns,
  • Filtering of opportunities.
Instead of scratching our head thinking how to do this in Visualforce, we laughed out loud and told the client that the solution will be available in 5 minutes :)

DataTables our Saviour

DataTables is a jQuery plugin which we will use to make the dream of our client come true. DataTables focuses on enhancing the user-experience on standard HTML tables.

Code

Below is a small code used to generate our table of Opportunities. Notice how we import our scripts and css for DataTables; you should normally put them in a Static Resource. At line 15, we called the dataTable function to initialise our table.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<apex:page standardController="Account">
    <apex:includescript value="//code.jquery.com/jquery-1.11.1.min.js" / >
    <apex:includescript value="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js" />
    <apex:stylesheet value="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css" />
    
    <apex:dataTable value="{!Account.Opportunities}" var="opp" styleClass="opp-table">
        <apex:column value="{!opp.Name}" headerValue="Name"/>
        <apex:column value="{!opp.StageName}" headerValue="Stage"/>
        <apex:column value="{!opp.Amount}" headerValue="Amount"/>
        <apex:column value="{!opp.CloseDate}" headerValue="Close Date"/>
    </apex:dataTable>
    
    <script>
        $(function(){
            $('table.opp-table').dataTable();
        });
    </script>
</apex:page>

Result



  1. Pagination controls
  2. Pagination size controls
  3. Sorting by clicking on column header. (currently sorted on Amount)
  4. Instant filtering capability over whole table.
Final words

This is a basic example of using DataTables in Visualforce. Part 2 coming soon...


Cheers & Happy Coding !!
Gulshan.