views:

539

answers:

4

I'm doing my first experiments with Grails and am looking for a way to have fields represented by a combobox (such as one-to-one domain associations and numbers with a narrow range constraint) to be optional, i.e. there should be an empty entry in the combobox.

How can this be achieved? I've tried both adding a nullable:true constraint and listing the fields in the optionals static property, but neither produces the desired result.

These are my domain classes:

class Customer {
    String name
}
class Book {
    static optionals = ['year','loanedTo','loanedSince']
    static constraints = {
    title(blank:false)
    author(blank:false)
    year(range:1900..new Date().getAt(Calendar.YEAR), nullable:true)
    loanedTo(nullable:true)
    loanedSince(min:new Date())
    }

    String title;
    String author;
    Integer year;
    Customer loanedTo;
    Date loanedSince;
}
+3  A: 

I've found that the nullable:true constraint actually does have the desired effect - however, it does not take effect immediately; you have to restart Grails to see it.

Michael Borgwardt
+1  A: 

If you've generated your scaffolding code, you'll also have to regenerate it so that the option is present.

Ted Naleid
A: 

The tag also has an attribute for a default, "not selected" value: noSelection. You can use it like this to have the drop-down default to "---" instead of your regular values: noSelection="${['':'---']}"

In the controller, the default value shows up as an empty string, as specified in the first part of the value.

Karsten Silz
+1  A: 

I don't think optionals is still supported: http://jira.codehaus.org/browse/GRAILS-472

Daniel Serodio
yes - nullable:true seems to be the "official" way to achieve this now.
Michael Borgwardt