Grails Scaffolding - define possible values for this property of a domain class
Asked Answered
K

2

6

I am new to Grails. I have a Person domain class as :

class Person {
    String firstName
    String lastName
    String gender
    Date dateOfBirth
}

And wondering if I can define possible values for a property - say gender as {M, F, U} so that these three values will be listed in combo box when using dynamic scaffolding for Person controller.

Here I just wanted to know if there is such feature in Grails framework? If such feature exists , then how can I use it?

Kamala answered 8/7, 2012 at 4:46 Comment(0)
P
5

From the documentation http://grails.org/doc/latest/guide/scaffolding.html, you should be able to use an inList constraint:

class Person {
    String firstName
    String lastName
    String gender
    Date dateOfBirth

    def constraints = {
        gender( inList: ["M", "F", "U"])
    }
}

This should scaffold to a select list for the gender field, depending on the version of Grails you're using. 2.0+ definitely does this.

Precede answered 8/7, 2012 at 5:40 Comment(0)
J
3

Here is an alternative solution

class Person {
    String firstName
    String lastName
    enum Gender {
        M(1),
        F(2),
        U(3)
        private Gender(int val) { this.id = val }
        final int id
    }
    Gender gender = Gender.U
    Date dateOfBirth

    def constraints = {
        gender()
    }
}

This will store gender in the database as an integer (1,2,3) and default the gender to U. The benefit here is you can rename what F, M, and U mean without handling a data migration.

Jerkin answered 9/7, 2012 at 1:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.