Creating a Client-Side Sortable List Using CMS

On often requested feature is the ability to do client side sorting of report data in an external application. With CMS, this can be done quickly and easily. For this example, we'll use HTML and Javascript.

To keep the example simple, we'll use a report that contains a straightforward list of data called “List1”. We'll ask for this report via CMS in JSON format, and we'll disable async to keep the code a little shorter.

Now that we've got the report data in a JSON object, we'll need to be able to sort it. We start off by creating a compare function that will compare two report table cells in the same column. A cell object that contains text data will have a valTyp property that tells us is the type of data in the cell. The val property tells us the raw data value. The compare function needs to return a positive value if a>b, 0 if a=b, and a negative value if a<b. For this example, the compare function will only work with numeric and text data, but extending the sorting to other data types is simply a matter of implementing the comparison.

Next, we need to render the table using javascript to dynamically generate the HTML. We start off by looking at the colTitles section of the list that gives us the table column headers. We'll also draw an up or down triangle beside the column that is currently being sorted and listen for a user clicking on a column header so that we can call a function called “reSort()” to resort the table.

Next, we need to render the table itself. There's only one level of grouping in the report, so we can take the rows directly as a javascript array. This allows us to use the Javascript sort() function to sort the data using the compare function we implemented. Note that when we used the compare function, we were looking at the cell's val property which gives us the raw data. However, for display purposes we want to use the fmtVal property which gives us the data as it was formatted in the report. Finally, if this is a descending instead of an ascending sort, we can simply call Javascript's reverse() function to reverse the order of the data array.

Applying a stylesheet to make the generated table look nicer, we get the following. Another alternative would be to use the style information that was contained in the JSON report object to preserve the look and feel from the original report.