Friday, 24 September 2010

Grails Tip: Sorting rows in table when the underlying data structure is a Set (unsorted)

I was having trouble with the display of a list of items in a table.  Each time I refreshed the page the order was different.  This is because the items are coming from a Set, which is unsorted.  I had to add a sort closure to the g:each as illustrated below:
<g:each in="${ quoteInstance?.quoteItems.sort{a,b-> a.id.compareTo(b.id)} }" status="i" var="q">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td><span class="buttons"><q:button controller="quote" action="selectQuoteItem" class="save" params="['id': quoteInstance?.id, 'quoteItemId':q.id]" value="${message(code: 'default.button.save.label', default: 'Select Quote Item')}" /></span>
<td>${fieldValue(bean: q, field: 'quantity')}</td>
<td>${fieldValue(bean: q, field: 'unitOfSale')}</td>
<td>${fieldValue(bean: q, field: 'unitPrice')}</td>
<td>${fieldValue(bean: q, field: 'materialGuidePrice')}</td>
<td>
<div class="buttons">
<q:button controller="quoteItem" action="edit" class="edit" params="['quoteId': quoteInstance?.id, 'id':q.id]" value="${message(code: 'default.button.edit.label', default: 'Edit')}" />
<q:button controller="quoteItem" action="delete" class="delete" params="['quoteId': quoteInstance?.id, 'id':q.id]" value="${message(code: 'default.button.delete.label', default: 'Delete')}" />
</div>
</td>
</tr>
</g:each>