Aydin
Aydin

Reputation: 331

How can Grails domain object members have default names based on a computed value?

This is what I'm trying to do:

class Test {

   String name

   static mapping = {
    name defaultValue: "test_${Test.count()}"
   }
}

So when a new "test" object is created the name is test_1, test_2, test_3 etc. depending on how many test objects already exist. The above does not work because "test.count was used outside of a Grails application"

Upvotes: 1

Views: 80

Answers (1)

kmera
kmera

Reputation: 1745

You could initialize the property instead of specifying the value via the mapping closure.

class Test {
    String name = "test_${Test.count()}"
}

or

class Test {
    String name = initName()

    private static String initName() {
        def count = Test.count()
        return "test_" + count
    }
}

Upvotes: 1

Related Questions