Grails - GSP Tag - sortableColumn

Tag - sortableColumn (Since 0.5)

Description

Renders a sortable column to support sorting in tables.

Parameters

  • property - name of the property relating to the field
  • defaultOrder (optional) - default order for the property; choose between asc (default if not provided) and desc
  • title (optional*) - title caption for the column
  • titleKey (optional*) - title key to use for the column, resolved against the message source
  • params (optional) - a map containing request parameters
  • action (optional) - the name of the action to use in the link, if not specified the list action will be linked
Attribute title or titleKey is required. When both attributes are specified then titleKey takes precedence, resulting in the title caption to be resolved against the message source. In case when the message could not be resolved, the title will be used as title caption.

Examples

<g:sortableColumn property="title" title="Title" />
<g:sortableColumn property="title" title="Title" style="width: 200px" />
<g:sortableColumn property="title" titleKey="book.title" />	 
<g:sortableColumn property="releaseDate" defaultOrder="desc" title="Release Date" />
<g:sortableColumn property="releaseDate" defaultOrder="desc" title="Release Date" titleKey="book.releaseDate" />

Pitfalls

Usually, you will use the sortableColumn tag to display the results of a query like Book.list(params). That works fine for every property of the domain class Book (like title ...) using
<g:sortableColumn property="title" title="Title" />
. But what if a Book has a publisher whose name you want to list as a sortable column either?
<g:sortableColumn property="publisher.name" title="Publisher's name" />
is not supported! What about transient properties? They aren't supported as well as we're asking the database here, and transients are non-persistent! What you need to do is change your controller to use Hibernate Criteria.

You can write your controller action like this:

def list = {
        if (!params.max) params.max = 10
        if (!params.offset) params.offset = 0
        if (!params.sort) params.sort = "title"
        if (!params.order) params.order = "asc"

def books = Book.withCriteria { maxResults(params.max?.toInteger()) firstResult(params.offset?.toInteger()) if (params.sort == 'publisherName') { publisher { order('name', params.order) } } else { order(params.sort, params.order) } } [books:books] }

Using

<g:sortableColumn property="publisherName" title="Publisher's name"/>
will allow you to sort by publisher's name then.