NerdGerl

Populating a select box in Grails with values from database

Posted by: nerdgerl on: August 20, 2009

A fairly common requirement is to populate values in a select box/drop down box with values from a database. It’s quick and easy to do in Grails.

  1. Inside your Contorller, create your query in the closure associated with your view. Eg. I’m going to create a new object that contains a list of values from that database and return it to the search.gsp view:
  2. def search = {
      def authors = Book.executeQuery("SELECT distinct b.author FROM Book b")
      [authors : authors]
    }

  3. Inside your search.gsp, add a select box that displays the list of countries:
    <g:select id="authorSelection" name="author" from="${authors}" value="" noSelection="['':'Please Select...']> 
  4. When you are reading the value back out of the form in your controller, simply use:
    params.author
  5. You’re done! Easy peasy.

EDIT: I recently found an official looking tutorial about how to do selects with grails here.

Tags: ,

3 Responses to "Populating a select box in Grails with values from database"

Thanks, didn’t use executeQuery but used the principle :-) ,

saw your lvl80 DK as well , pick a good class next time :p

Hey Paul. Thanks for visiting my site. You sure you don’t have me mixed up with someone else… I have a level 80 lock.. horde of course, no DK’s for me ;)

How about really long lists… How do I handle that…

Let’s say,

I am making a Book. Each book as 1 Author, and a Title.

I have an Author with a first and last name.

Each book, has 1 author, and in the drop down list, you choose the Author you want.

Now Imagine, I have 100 Author entries….

How do I handle the long list of authors?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.