Monday, August 18, 2008

Remembering state of a Grails list page

With the default Grails scaffolding each time you navigate away from the list page (e.g. going to the show page) the state of the list is lost when you return. This can be annoying when you paged to a certain page within the list.

It's easy to make your application remember the state of your list pages. See the example below which is a modified list action:

def list = {
if (!session[controllerName]) session[controllerName] = [:]
if (!session[controllerName]?.max) session[controllerName].max = 10
if (!session[controllerName]?.offset) session[controllerName].offset = 0
if (!session[controllerName]?.sort) session[controllerName].sort = "id"
if (!session[controllerName]?.order) session[controllerName].order = "asc"

params.max = session[controllerName].max = params.max ?: session[controllerName].max
params.offset = session[controllerName].offset = params.offset ?: session[controllerName].offset
params.sort = session[controllerName].sort = params.sort ?: session[controllerName].sort
params.order = session[controllerName].order = params.order ?: session[controllerName].order

[ authorList: Author.list( params ) ]

It stores (per controller) the needed params in the session and when performing the action again, it will take the values from session and your list page remembers its state.


Andres Almiray said...

You may want to use a bit of Elvis magic in there ;-)

params.max = session[controllerName].max = params.max ?: session[controllerName].max

Lee said...

Thanks for the handy tip Marcel!

You missed the opportunity to use the awesome elvis operator in that section of code where you're assigning values to params.max etc ;)

params.max = session[controllerName].max = params.max ?: session[controllerName].max

Marcel Overdijk said...

Thanks guys. I changed the code to use the Elvis operator.