Tuesday, November 1, 2005

Sorting your Domino views with JavaScript


By Colin Neale

Have you ever wanted to be able to sort your Domino views in the browser in just the same way that you can from the Notes Client? This article shows one way to achieve column sorting on the Web using some simple JavaScript routines. I use a similar method to allow the sorting of search results in my C-Search products.

Create a simple database

I started by creating a database. I added a form and two fields: "Title" and "Author". Next I added some sample documents. Figure A shows these documents when viewed from the Notes Client.


Here's a simple database contents viewed in Notes. (click for larger image)

Here sorting is achieved by clicking on each column header. I will now show you how to reproduce this same functionality in the browser.

Create a Web view

I proceeded to create a view for the browser. I used multiple columns to make the code easier to follow but you could group all of the HTML into a single column if you prefer. Each column in my Web view is detailed below. The Column-1 formula is simple:


Set to sorted ascending and hidden because we don't want the browser to see it. The Column-2 formula has some table tags:

"<tr title=&#92"row&#92">"

This defines the start of each table row. Note that I have given the row a &quot;title&quot; attribute. I use title attributes of the &quot;tr&quot; and &quot;td&quot; tags to give me access to the data that I want to sort on.

The Column-3 formula is where some of the hard work begins:

_db := "/" + @ReplaceSubstring(@Subset(@DbName;-1);"&#92&#92";"/");
_url := _db + "/0/" + @Text(@DocumentUniqueID) + "?OpenDocument";
"<td width=&#92"50%&#92"  title=&#92"booktitle&#92" abbr=&#92"" + @UpperCase(Title) + "&#92"><a href =&#92"" + _url + "&#92">" + Title + "</a></td>"

This is the first column of the HTML table. It displays the book titles as links. Note, that I use the &quot;title&quot; attribute of the &quot;td&quot; tag here just as I did for the &quot;tr&quot; tag above. For the table columns however I also use the &quot;abbr&quot; attribute to hold the value that I wish to sort by.

Column-4 formula adds a bit more:

"<td width=&#92"20%&#92"  title=&#92"author&#92" abbr=&#92"" + @UpperCase(Author) + "&#92">" + Author + "</td>"

The second table column displays the value in the Author field.

The Column 5 formula ends the table row:


Finally, I enabled the &quot;Treat view contents as HTML&quot; property and saved the view.

Create a form to show the view through

Next I created a $$ViewTemplateDefault form to display the view created above. I added the following HTML code to the top of the form.