Sunday, May 1, 2011

How can fields in Grails represented by a combobox be made optional?

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;
}
From stackoverflow
  • 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.

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

  • 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.

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

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

0 comments:

Post a Comment