Tuesday, December 2, 2008

Using the Filter Plugin for Grails

The filter plugin is a very useful tool if you want to be able to narrow down your lists in a convenient way.   For more info on the plugin check out http://www.grails.org/Filter+plugin.

Once you install the plugin, also check out the example app.  Some of the things that were not so obvious when using Filter are as follows:

1. Version 0.1 only works for the "list" action.  Make sure you only use this on the controller/list type of action.  Any other action, and it will not work.

2. Make sure you include prototype and scriptaculous in the header of your list.gsp.  This is important because the plugin will just sit there and do nothing without these libraries.

3. Use a template called _list.gsp for your list table.  Filter currently expects this.

4. Name your model data after your plugin with the "List" keyword added.  For example: if your controller is foobar, make sure your data model contains and is expecting a "foobarList" to iterate over for the list.  If you re-name this to something else, it won't work.

5. Add a div tag where the id is "list"around your entire list in the template.  Filter expects this when rendering.  (you can see an example in the example app you downloaded)

6. It doesn't hurt to initialize max and offset in your controller. 

class foobar {
  def list = {
    if (!params.max) params.max = 10
    if (!params.offset) params.offset = 0 

7. Paginate requires "total" to be in the model.  Define total and return it in your controller.

One current limitation to the Filter plugin is this: If you want to use a narrowed result set (i.e. Foobar.findAllByStatus("Active")), and you set "total" in your controller using Foobar.countByStatus("Active"),  Filter only takes the count from the class when it finishes filtering.  That is, it does a clazz.count() which is basically a Foobar.count().  It also just takes the list from the parameters given (i.e. Foobar.list(params)).  What happens is, your count will be off in your pagination and result set after filtering.  You will see more data in your results after you  filter than the initial list.  You'll have to either modify the FilterController to fix this, or wait for a new release where this might be addressed.

This is a great plugin with lots of potential.