Sunday, May 20, 2012

Grails Dynamic Dropdown

Recently I had a UI requirement where a customer wanted to select values from two separate dropdowns. The value of the first dropdown essentially filtered the values for the second dropdown. Given the financial projects we support are not heavy on UI requirements, I had to do some initial learning and experimentation to yield a good implementation. This blog entry details the how to implement dynamic dropdowns in Grails with ajax and minimal JavaScript.

Example Problem

A contrived for dynamic dropdowns can be described below:

A user would like to select a sports team for a city. The user first selects a value for a dropdown to choose a city. A second dropdown is filtered with the sports teams within that city. An example to clarify:
  • The user selects Dallas as the city in the first dropdown. The second dropdown now displays values: Mavericks, Cowboys and Rangers.
  • The user selects Pittsburgh as the city in the first dropdown. The second dropdown now displays values Steelers, Pirates, and Penguins.

High Level Design in Grails 

Before we get into the details, we can take a step back and describe how we can accomplish a dynamic dropdown in the grails framework.
  • On a gsp page, create a select dropdown with the list of cities.
  • On change of the city dropdown, send an ajax call to the server with a param of the city selected.
  • A controller on the server receives the parameter and looks for teams based on the city selected.
  • Return a template with a new select dropdown for the teams, providing a model with the filtered list of teams.
We will continue below with code snippets. The code was demoed with Grails 2.0.

Domain Objects
The domain objects for this example are quite simple: A City object with a name, and a Team object.