Sort Subforms

You probably already knew it was possible to re-order (and hence sort) a group of subforms.  But in case you didn’t — or in case you needed a sample, here you go.

In the sample, the column headings are button fields.  Their click event sorts the rows by the values in that column.  If you click again it will sort in descending order.

I centralized the sort methods into a script object that ought to be re-usable in other contexts:

/**
* Sort a group of subforms.  Calling this the first time will sort
* ascending. Calling it again will toggle to descending.
* @param vButton the button field used to initiate the sort. 
*  We store the current sort order in the button rawValue property.
* @param vInstanceManager the instance manager of the subforms to
*  be sorted
* @param vSortFieldName the name of the field in the subforms used
*  to sort.  Null values always sort to the beginning.
*/
function sort(vButtonField, vInstanceManager, vSortFieldName)

/**
* Sort a group of subforms.  Calling this the first time will sort
* ascending. Calling it again will toggle to descending.
* @param vSubformInstance one instance of a subform in the set of
*  subforms to be sorted
* @param vFieldName the name of the field used to sort
* @param bAscending boolean: if true, sort in ascending order,
*  otherwise descending.
*/
function performSort(vSubformInstance, vFieldName, bAscending)

Note that sorting subforms will also cause their underlying data to also be re-ordered.

Notes

Rather than embarrass myself by implementing a rookie bubble sort, I used the JavaScript Array.sort() method.  Of course, this meant figuring out how to set up a sorting function and letting it have access to the sort parameters (sort field and sort order).  But figuring out how to store these under <extras> was easier than trying to impress you with a fancy heapsort algorithm.

I generated the sample data at this very clever website: http://www.generatedata.com/ 

Deep End

If you sort a very large set of subforms, you might run into performance issues.  If you need to improve the performance, try sorting the underlying data DOM using the remove/insert methods on the nodelist.  After re-ordering the data you would do an xfa.form.remerge() and the subforms should show up nicely sorted.