Has anyone ever tried to replicate the alphabet sorting functionality you see in the list views? Any ideas on how to achieve this?

  • Some clarification would be helpful - are you trying to replicate the end-user javascript sorting that you get on the list view table, or just sorting records in general? – jkraybill Feb 15 '13 at 5:16

This functionality already exists on List using the sort method:

Sorts the items in the list in ascending order.

In the following example, the list has three elements. When the list is sorted, > the first element is null because it has no value assigned while the second element has the value of 5:

List<Integer> q1 = new Integer[3];

// Assign values to the first 
// two elements
q1[0] = 10;
q1[1] = 5;

// First element is null, second is 5
system.assertEquals(q1.get(1), 5);


Using this method, you can sort primitive types, SelectOption elements, and sObjects (standard objects and custom objects). For more information on the sort order used for sObjects, see List Sorting. You can also sort custom types (your Apex classes) if they implement the Comparable interface.


I think you're asking about how best to replicate the table sorting that happens when the user clicks a column header. If that's the case, you have basically two sorting options and three client-side table rendering options.

Sorting: client-side or server-side. I'd opt for client-side if your total record set is small, as this is MUCH faster to the end user. Use server-side sorting if your record set is large, or if you need some very complex sorting logic that would be unwieldy in Javascript (extremely unlikely). If you do opt for server-side sorting, be aware that the default alphabetic sorting for Apex strings is case-sensitive; you'll have to work around this in your code, usually by implementing your own sort logic.

Table rendering: either use a standard VisualForce table control (i.e. DataTable) with sorting actions on the column headers (example here), or build your own HTML table (I would not recommend this but it's common), or use an off-the-shelf Javascript/HTML library. In my experience, the ExtJS library is incredibly full-featured for many things like this, including building data tables that have lots of fancy user-side features including sorting and row highlighting, but it's not free. (It's also used extensively by Salesforce within their products). There are plenty of free options based on (among other libraries) jQuery, including this datatables plugin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.