Analytics

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.

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!

110 comments:

  1. Grails 2.0.1 complains about this line

    params: ''city.id=' + this.value',

    Even after getting around that, this code won't dynamically fill the teams dropdown - however, the relationships do work.

    Did you test this code? Do you have a working sample project which you might share?

    Thanks

    ReplyDelete
  2. This code is working code that i pasted on to the site. Unfortunately the tool i used to format html on to the blog left out a '/' char, and it was escaped.

    the snipper should lool like this:

    params: '\'city.id=\' + this.value',

    If you would like a zip of the code, send me an email please. I will be glad to send it to u. I have corrected on the site.

    Thanks for catching that!

    ReplyDelete
  3. Can you send me the code. Much appreciated.

    ReplyDelete
  4. @cmtopinka

    i sent the code to cmtopinka@gmail.com. Is that your email? If not please let me know

    ReplyDelete
  5. Hi
    can u send me the code to karthiknagtaurus@gmail.com

    ReplyDelete
  6. Hello, can you also email me the code at rachel_bird@taylor.edu?
    Thanks so much.

    ReplyDelete
  7. Plz u send me the code kamonpop@gmail.com

    ReplyDelete
  8. PLease send me the code at saurabhkr1@yahoo.com . Many Thanks in advance

    ReplyDelete
  9. Hello, Can you send me the code, please? Thank you
    lletuga15@gmail.com

    ReplyDelete
  10. Hi , can you please send me the code, too? I tried to google it with no luck.
    erik.marencik[at]gmail[dot]com

    ReplyDelete
  11. i have to create the samething , but the value of first select to be tested. for eg: it belongs to province ="BC" something like that.
    One morething , these two select tag to be used in the create.gsp page does it affect other user data already entered?
    Can you please give me reply and code to my id :kalpana.vasan@gmail.com

    ReplyDelete
  12. Hi. I was wondering if you could share the source with me as well. Thank you! ahdunn@gmail.com

    ReplyDelete
  13. send me please too!
    mihailorama@gmail.com

    ReplyDelete
  14. send me please too!

    rafra_raja@yahoo.com.mx

    ReplyDelete
  15. Hi can you send me the code also. jerika.legasto@gmail.com
    Thank you.

    ReplyDelete
  16. Send me a copy please!

    elisieldavila@gmail.com

    Thank you.

    ReplyDelete
  17. Could you please send a copy of this code to jobrien1956@gmail.com

    Thanks

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Please send a copy to javier7co@gmail.com
    Thanks

    ReplyDelete
  20. What is the path of the template .gsp file?
    Could you please send a copy of this code to jool49@gmail.com
    Thank you

    ReplyDelete
  21. Please send a copy of the code to andrelink14@gmail.com.
    Thank you

    ReplyDelete
  22. Could you please send a copy of this code to hemantgp@gmail.com

    Thanks

    ReplyDelete
  23. Hello, could you please send a copy of this code to dimitris-ts@hotmail.com

    Thanks you!!

    ReplyDelete
  24. Hello, could you please send a copy of this code to hameedr09@gmail.com

    Thanks you!!

    ReplyDelete
  25. This is the right blog. it's far very interesting weblog ever. thank you for giving one of these first-rate article. for more information please check the site
    oracle cloud fusion financials

    ReplyDelete
  26. Usually the blog you posted is very useful to us thanks for posting this blog.

    To find Best Training institutes can search in our Calfre.com it is very easy to find the complete details about all Training's Centers Find more information click here

    ReplyDelete
  27. Wow, this blog is very nice I really like your blog and i am Impressed thank you very much for posting this blog.

    To find Best Training institutes can search in our Calfre.com it is very easy to find the complete details about all Training's Centers Find more information click here

    ReplyDelete
  28. This post is very informative for everybody. I would like to appreciate your work for good accuracy and got informative knowledge from here.
    To find Best Training institutes can search in our Calfre.com it is very easy to find the complete details about all Training's Centers For more information Click Here


    ReplyDelete
  29. I recently came across your blog and have been reading along. I thought I would leave my first comment.
    Java training in Chennai

    Java training in Bangalore

    ReplyDelete
  30. PirateBy Supplies Top Famous Cracks, Serial Keys, Patches, Cracked Software, PirateBy also Provide WordPress Nulled Themes & Plugins Absolutely Free.

    ReplyDelete
  31. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
    RPA Training in chennai |RPA Training course chennai

    ReplyDelete
  32. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
    matlab training in chennai



    ReplyDelete
  33. The first course you may want to take advantage of is the PAT testing course, cursos de ti

    ReplyDelete
  34. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    AWS training in chennai | AWS training in anna nagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  35. Thanks for sharing this informative content , Great work
    Leanpitch provides online training inScrum Master during this lockdown period everyone can use it wisely.
    Advanced Scrum Master Training

    ReplyDelete
  36. Hi,
    I things it's an amazing piece of content. I would like to appreciate your efforts.
    We are providing wonderfull digital marketing agency. If you are looking for these services we are here for you. Feel free to visit our website.

    ReplyDelete
  37. you described it very beautifully thank you. Yellowstone Coat

    ReplyDelete
  38. EasyWay Logistics.!!
    Looking for a Customs clearance Service, Truck service, Freight forwarder, Shipping a Cargo, Import & Export ..??
    Transporters in India
    Cargo Agents
    Custom Clearing Agents
    C&F Agents
    Second Hand Container Dealers
    Air Cargo Agents

    ReplyDelete
  39. Really very Interesting Article, Thanks for sharing it. Webocity is best website designing company in delhi , Best Website development company in Delhi, We Offer Best Digital Marketing services in Delhi.

    ReplyDelete
  40. Hailing from the prestigious PGIMER, Chandigarh, Dr. Manish Budhiraja, is a dynamic & experienced Neurosurgeon whose expertise is in complex Brain & Minimally Invasive Spine surgeries. He has specialization in Brain and Spinal Tumor surgeries, Minimally Invasive Spine Surgeries, Spinal trauma and Fixation, Pituitary Tumors and Functional Neurosurgery including Deep Brain Stimulation
    Doctor Name- Dr. Manish Budhiraja {MBBS, MS (Surgery), M.Ch (Neurosurgery)}
    Address- Alchemist Hospital Rd, Sector 21, Budanpur, Panchkula, Punjab 134112
    Phone- 7888900544

    ReplyDelete
  41. I will definitely write all these addresses down and try them as soon as I could! Love the remark about the bartender who looks like Johnny Depp! Great post! Mens Shearling Coat

    ReplyDelete
  42. Do you need an urgent loan of any kind? Loans to liquidate debts or need to loan to improve your business have you been rejected by any other banks and financial institutions? Do you need a loan or a mortgage? This is the place to look, we are here to solve all your financial problems. We borrow money for the public. Need financial help with a bad credit in need of money. To pay for a commercial investment at a reasonable rate of 3%, let me use this method to inform you that we are providing reliable and helpful assistance and we will be ready to lend you. Contact us today by email: daveloganloanfirm@gmail.com Call/Text: +1(501)800-0690 And whatsapp: +1 (315) 640-3560

    NEED A LOAN?
    Ask Me.

    ReplyDelete
  43. Thanks for sharing informative content, Great work.

    To crack Scrum master interview: Scrum master interview questions

    ReplyDelete
  44. Thank you very much for providing important information. All your information is very valuable to me.
    Village Talkies a top-quality professional corporate video production company in Bangalore and also best explainer video company in Bangalore & animation video makers in Bangalore, Chennai, India & Maryland, Baltimore, USA provides Corporate & Brand films, Promotional, Marketing videos & Training videos, Product demo videos, Employee videos, Product video explainers, eLearning videos, 2d Animation, 3d Animation, Motion Graphics, Whiteboard Explainer videos Client Testimonial Videos, Video Presentation and more for all start-ups, industries, and corporate companies. From scripting to corporate video production services, explainer & 3d, 2d animation video production , our solutions are customized to your budget, timeline, and to meet the company goals and objectives.
    As a best video production company in Bangalore, we produce quality and creative videos to our clients.

    ReplyDelete
  45. Incredibly conventional blog and articles. I am realy very happy to visit your blog. Directly I am found which I truly need. Thankful to you and keeping it together for your new post…

    AWS Training in Hyderabad

    ReplyDelete
  46. Do you need an urgent loan of any kind? Loans to liquidate debts or need to loan to improve your business have you been rejected by any other banks and financial institutions? Do you need a loan or a mortgage? This is the place to look, we are here to solve all your financial problems. We borrow money for the public. Need financial help with a bad credit in need of money. To pay for a commercial investment at a reasonable rate of 3%, let me use this method to inform you that we are providing reliable and helpful assistance and we will be ready to lend you. Contact us today by email: daveloganloanfirm@gmail.com Call/Text: +1(501)800-0690 And whatsapp: +1 (501) 214‑1395

    NEED A LOAN?
    Ask Me.

    ReplyDelete
  47. thanks for the valueable content. information is nicely written and understandable!
    Are you looking for the best digital marketing training in Jaipur? You are in right place. Dzone is offering you the best digital marketing training with a great learning experience and practical exposure. We offer you practise oriented real-time digital marketing course. To know more contact us at 9829708506
    Or can visit our website: http://bit.ly/digitaldzone

    ReplyDelete
  48. DO YOU NEED A PERSONAL/BUSINESS/INVESTMENT LOAN? CONTACT US TODAY VIA WhatsApp +19292227023 Email drbenjaminfinance@gmail.com

    HELLO
    Loan Offer Alert For Everyone! Are you financially down and you need an urgent credit/financial assistance? Or are you in need of a loan to start-up/increase your business or buy your dream house. Are you in search of a legit loan? Tired of Seeking Loans and Mortgages? Have you been turned down by your banks? Have you also been scammed once? Have you lost money to scammers or to Binary Options and Cryptocurrency Trading, We will help you recover your lost money and stolen bitcoin by our security FinanceRecovery Team 100% secured, If you are in financial pains consider your financial trauma over. We Offer LOANS from $3,000.00 Min. to $30,000,000.00 Max. at 2% interest rate NO MATTER YOUR CREDIT SCORE. GET YOUR INSTANT LOAN APPROVAL 100% GUARANTEED TODAY VIA WhatsApp:+19292227023 Email: drbenjaminfinance@gmail.com


    ReplyDelete
  49. Fantastic article! Many thanks for the exciting blog posting! I like the informative article from you. Will look forward for more updates. Good Job, Keep it up..

    ui ux course
    PHP Course
    ui ux course
    .net course singapore
    python course

    ReplyDelete
  50. Welcome to CapturedCurrentNews – Latest & Breaking India News 2021
    Hello Friends My Name Anthony Morris.latest and breaking news

    ReplyDelete
  51. Very Informative blog thank you for sharing. Keep sharing.

    Best software training institute in Chennai. Make your career development the best by learning software courses.

    power bi course in Chennai
    Docker Training in Chennai
    android training in chennai
    ios training in chennai
    Xamarin Training in Chennai
    msbi training in chennai
    Informatica Training in Chennai

    ReplyDelete
  52. This article explains to you the Scope of Digital Marketing in India 2020 and the career opportunities on Digital Marketing.

    ReplyDelete
  53. I simply wanted to thank you so much again. I am not sure the things
    that I might have gone through without the type of hints revealed by
    you regarding that situation.
    oracle course in chennai
    ASP Dot Net Training in Chennai
    C Sharp Training in Chennai

    ReplyDelete
  54. Appreciative for sharing your contemplations. I really like your undertakings and I will hold tight for your further evaluations. Everything is incomprehensibly open with a positive depiction of the troubles. It was really enlightening. Your site is important. Thankful for sharing! Nasa jacket

    ReplyDelete
  55. All things considered I read it yesterday yet I had a few musings about it and today I needed to peruse it again in light of the fact that it is very elegantly composed.

    ReplyDelete
  56. 360DigiTMG, the top-rated organisation among the most prestigious industries around the world, is an educational destination for those looking to pursue their dreams around the globe. The company is changing careers of many people through constant improvement, 360DigiTMG provides an outstanding learning experience and distinguishes itself from the pack. 360DigiTMG is a prominent global presence by offering world-class training. Its main office is in India and subsidiaries across Malaysia, USA, East Asia, Australia, Uk, Netherlands, and the Middle East.

    ReplyDelete
  57. Thank you for shearing post amazing this is post very useful for me. Cruella Jacket

    ReplyDelete
  58. I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.

    ReplyDelete
  59. Tableau training institute in Hyderabad can be a ticket to your fortunate tableau career. Dashboards, tableau desktop, Tableau online, charts, and many other key features of tableau this is best for you have interest visit my website link http://tableautrainings.in/

    ReplyDelete
  60. I Appreciate this post. It's a very informative and useful.

    ReplyDelete
  61. Amazing, glad realm. I would at the rear of to write down when this as well - taking time and cement hard play a situation to make a comfortable article... anyway I put things off something over the top and in no way, shape or form appear to profit started. much thanks to you despite the fact that. thanks! Driver Toolkit Crack

    ReplyDelete
  62. much obliged to you for taking the length to examine this, I have a firm opinion roughly it and commend getting to know additional going vis- On the off chance that feasible, as you benefit speed, could you considerations refreshing your weblog long past helper assessment? it's miles the total obliging for me. thanks! Office 2010 Activation Crack

    ReplyDelete
  63. React JS Training in Hyderabad

    ReplyDelete
  64. I really appreciate your valuable efforts and it was very helpful for me. Thank you so much...!
    Uncontested Divorce Process in Virginia
    Cheap Uncontested Divorce in VA

    ReplyDelete
  65. Nice article
    Guidelines
    http://www.jeevisoft.com

    ReplyDelete
  66. Step-by-Step Hacking Tutorials about WiFi hacking,
    Kali Linux, Metasploit, exploits, ethical hacking, information security, malware analysis and scanning
    hacking Tutorial

    ReplyDelete
  67. You have performed a great job. I will certainly dig it and individually suggest my friends. I’m sure they will be benefited from this web site. Grease Pink Ladies Jacket

    ReplyDelete
  68. I wholeheartedly congratulate the writer of this post for explaining the difficult concepts of data science in a simple and easy-to-understand manner. My only regret is that I didn’t read this post earlier. I have made many career decisions in my life after reading this, and have no regrets whatsoever to date.data science course in KL

    ReplyDelete
  69. Thank you sharing the informative article. Jason Momoa Snakeskin Jacket This is useful article for us.

    ReplyDelete
  70. Kids can learn a lot of fresh and intriguing things from this area. You are doing wonderful job for the new generation of kids, which makes me pleased. Post more fantastic blogs like this.Star Trek Picard Season 3 Leather Jacket

    ReplyDelete
  71. i relished, i would clearly like a good deal extra statistics with this, specifically argue along (not too i simply would need…haha). You truely placed the state-of-the-art spin with a topic thats been discussed for decades. Super stuff, just exquisite! It's miles a totally thrilling weblog publish. I often visit your posts for my project's help approximately diwali bumper lottery and your outstanding writing competencies actually go away me bowled over เพื่อนฟุตบอล

    ReplyDelete
  72. Thanks for sharing this post. Know about Bitwissend, web development company in cochin.

    ReplyDelete
  73. Blogs can be an outlet for satire, providing readers with light-hearted content to brighten their day. Nord VPN Offer Blogs can document personal journeys, such as weight loss transformations.

    ReplyDelete
  74. Thanks for sharing this post. Know about Kidangeth Enterprises, steel door dealers in Kottayam.

    ReplyDelete
  75. This blog can help each and every readers and thank you for sharing this informative content, it was really worth reading it. Here we present our informative blog on Nepal to Bhutan travel to have a wonderful reading.

    ReplyDelete
  76. Unlock seamless transactions with WebPays – among the best credit card payment solution ! Choose WebPays for a streamlined payment experience that enhances your bottom line. Bookmark your success today!


    ReplyDelete
  77. Experience greater control over security rules and customization with white-label payment gateway solutions from ITIO Innovex. Contact us now to get the best deal to delight and win more customers.

    ReplyDelete
  78. For the most current and accurate information on Kenya trade statistics, I recommend checking Import Globals. For more information about global import export data visit our website.
    Kenya Import Data

    ReplyDelete
  79. Fantastic post! Your insights really resonate with me and have given me a fresh perspective on the topic breast nipple shield. Looking forward to reading more from you!

    ReplyDelete
  80. Embedded system training covers the design, development, and programming of embedded systems, which are specialized computing systems designed to perform specific tasks within larger systems or devices. Training typically includes topics such as microcontroller architecture, firmware development, real-time operating systems, device drivers, and interfacing with peripherals.

    ReplyDelete
  81. Great work, Thanks for sharing this informative content . embedded systems course in hyderabad.

    ReplyDelete
  82. I’ve read about this topic several times, but never has it been presented in such a clear and straightforward manner. The writer really did an exceptional job of breaking it down. It’s rare to find such a well-explained piece—truly impressed! Visit our link for ISO 9001 Certification In Saudi Arabia


    ReplyDelete
  83. This blog is truly wonderful. I've read it aloud to my friends and my relatives.

    ReplyDelete
  84. Cool and that i have a tremendous offer you: How Much Are House Renovations Stardew Valley log home restoration near me

    ReplyDelete
  85. This is the best blog design and article. Very nice job. Thank you very much...
    AWS Devops training in hyderabad

    ReplyDelete
  86. Jaypee India Ltd makes strong concrete mixer machine for building work. These machines mix cement, sand, and water evenly to make good concrete. Easy to use and long-lasting, Jaypee concrete mixers help save time and give the best results for your projects.

    ReplyDelete