Pages

Thursday, January 04, 2007

Java : Sorting the table rows on a particular column

Assumption:
1. A table with a already sorted order is getting displayed on the screen.
2. you know the ID of each of the in the table.
3. The each row of the table is an object in an array.

I am not writing the code as such, but just presenting the idea of sorting the table based on the column header clicked. One way is using common controls, which i rather not use. I am trying to present the most simplest idea of sorting.

Firstly, write the scriplets in which we write a comparator for each column we want to sort and sort the collection using the same.
Next write the javascript function for each of the sorting required which sets the corresponding to the value required from the sorted collection.
Lastly, call the function on click event of the column header.

I briefly write code snippets to make the idea more clear.

[%//scriplets
ExampleForm exampleForm = (ExampleForm)request.getAttribute("exampleForm");
List rowObjects = exampleForm.getRowObjects();

Collection.sort(rowObjects, new Comparator(){
public int compare(Object a, Object b) {
RealObject objectOne = (RealObject)a;
RealObject objectTwo = (RealObject)b;

[On Condiditions] return 1 or -1 or 0

}
});
%]

function sortTypeOne(){//javascript
document.getElementById('td00') = [%= rowObjects.get(0).getRowData() %]
document.getElementById('td10') = [%= rowObjects.get(1).getRowData() %]
.
.
[continue from here as many td's you want; You can also use struts to iterate over the collection here and setting the corresponding to the value required. The data inside the getElementById() can also be filled when you iterate using struts.{logic:iterate tag}]
}

[%// scriplets
Collection.sort(rowObjects, new Comparator(){
public int compare(Object a, Object b) {
RealObject objectOne = (NewRealObject)a;
RealObject objectTwo = (NewRealObject)b;

[On New Condiditions] return 1 or -1 or 0

}
});

%]

function sortTypeTwo(){//javascript
document.getElementById('td00') = [%= rowObjects.get(0).getRowData() %]
document.getElementById('td01') = [%= rowObjects.get(1).getRowData() %]
.
.
[continue from here as many td's you want; You can also use struts to iterate over the collection here and setting the corresponding to the value required. The data inside the getElementById() can also be filled when you iterate using struts.{logic:iterate tag}]
}

Table structure approximately is shown below.

[table]
[tr]
[th onclick="sortTypeOne()"/]
[th onclick="sortTypeTwo()"/]
.
.
.
[/tr]
[tr]
[td id='td00'/]
[td id='td01'/]
.
.
.
[/tr]
[/table]

replace '[' or ']' respectively with '<' or '>'