Search code examples
selectgrailsgsp

Grails f:field display selected dropdown


Hi I am very new in Grails and I have a very simple question in grails and I hope someone can help me.

I have a simple domain class Person as follows:

class Person {

    String  name    //  name of the person
    Date    dob     //  date of birth

}   // end of class

I already have a few Person entries in my database.

In another form, I want to let the users select the name of the person whose age is above 21 from a dropdown list. Right now it looks like this:

<fieldset class="form">

    <f:field bean="Person" property="name" />

</fieldset>

How do I filter all the other people from the database and only display the names of the people who above 21 years old?

Thank you so much in advance!


Solution

  • Search for the people who are older than 21 years old in the controller, then pass it to the gsp for display. Something like this:

    import groovy.time.TimeCategory
    
    def create() {
    
    // all your other codes
    def adults = Person.findAllByDobGreaterThanEquals(new Date() - 21.year) 
    
    // other codes....
    respond new Person(params), model:[adults :adults]
    }
    

    Then display it in the gsp with the resultset.

    <fieldset class="form">
    
        <f:field bean="Person" property="name" >
            <g:select name="name" from="${adults}" optionKey="id" />
        </f:field>
    
    </fieldset>