DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Grails Dynamic Dropdown

Nirav Assar user avatar by
Nirav Assar
·
May. 30, 12 · Interview
Like (0)
Save
Tweet
Share
22.44K Views

Join the DZone community and get the full member experience.

Join For Free
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.

package dropdown

class City {

  String name

  static hasMany = [teams: Team]

  static constraints = {
  }
}

package dropdown

class Team {
  
  String name

  static belongsTo = Team

  static constraints = {
  }
  
  String toString() {
    name
  }
}

Gsp Page

A gsp page contains a list of the cities directly from a GORM call. This is commonly performed and demonstrated by the default generated grails gsp pages. Note the use of remoteFunction. This is a grails gsp utility which makes an ajax call to the server and provides 'update' for the section of the dom to be updated on return.

For the team dropdown, we will start off with a an empty select tag. Below is a snippet.

<g:select name="city.id" from="${City.list()}" optionKey="id" optionValue="name"
                noSelection="['':'Choose City']"
                onchange="${remoteFunction (
                        controller: 'city',
                        action: 'findTeamsForCity',
                        params: ''city.id=' + this.value',
                        update: 'teamSelection'
                )}" />
		....
		
		<td id="teamSelection" valign="top">
		  <select>
			<option>Choose Team</option>
		  </select>
		</td>

Controller used for Filtering

The controller will have a closure which takes in the city id, and then uses it to provide the teams associated with the city. This closure is invoked via ajax. The closure renders a template and a model.

The def dynamicDropdown closure is just used for navigation. By convention its renders the gsp of the same name.
package dropdown

class CityController {

  static scaffold = City

  // just navigation to the gsp
  def dynamicDropdown = {
  }

  def findTeamsForCity = {
    def city = City.get(params.city.id)
    render(template: 'teamSelection', model:  [teams: city.teams])
  }
} 

Template

The template is used to replace a section of the dom in the gsp. It accepts any model that is provided.
<!-- This template renders a drop down after a city is selected -->

<g:select name="team.id" from="${teams}" optionValue="name"
          optionKey="id"/> 



Conclusion

There are multiple ways to accomplish a dynamic dropdown. Native jQuery can be used, or even native JavaScript. I chose to utilize the built-in functions of grails and lessen my dependency on client side programming. This proved to be clean, quick and quite simple
Grail (web browser)

Published at DZone with permission of Nirav Assar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Orchestration Pattern: Managing Distributed Transactions
  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • When Should We Move to Microservices?
  • Steel Threads Are a Technique That Will Make You a Better Engineer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: