Search code examples
grailsgroovygsp

Grails: How do i select from a list of previously created objects in my view?


Let's say i have the following classes:

package test

class Person {
    String name

    static hasMany = [stuff:Stuff]

    static constraints = {
    }
}

and package test

class Stuff {
    String stuff

    static belongsTo = Person

    static constraints = {
    }
}

When i implement the view for Person i want to be able to select from a list of previously created stuff. How do i achieve that? I see that, when i use scaffolding Grails generates that drop down menu where i can do that but since i a designing my own views i would like to understand how that is done.

Thank you.


Solution

  • Probably good to start be reviewing the documentation for the select tag here: https://gsp.grails.org/latest/ref/Tags/select.html

    A simple example to present a list of all Stuff would look like:

    <g:select name="stuffSelect" from="${Stuff.list()}" optionKey="id" optionValue="stuff"/>
    

    This should give you a dropdown of all Stuff in your database, displaying the String value to the user, but submitting the DB ID when the form submits.