Tuesday, August 19, 2008

Remembering state of a Grails list page (2)

Here is a enhanced version of remembering the state of your Grails list page using a rememberListState method. Just pass in a map of params you want to store in the session and want to use in the list query. The specified param values act as default values.

Controller code:

private rememberListState(stateParams) {
// get (or initialize) session state params
def sessionStateParams = session[controllerName] = (session[controllerName] ?: [:])
// store state params and its values in params and session object
// (1) use params (2) or use session (3) otherwise use default value
stateParams.each { k, v ->
params[k] = sessionStateParams[k] = (params[k] ?: (sessionStateParams[k] ?: v))

def list = {
rememberListState([max: 10, offset: 0, sort: id, order: 'asc'])
[ authorList: Author.list( params ) ]

I think you could even add this rememberListState() method to all Controller classes using the ExpandoMetaClass.

No comments: