rsijaya
rsijaya

Reputation: 169

Import domain in constraints

I have 2 domain classes

class a {
    String name
    static constraints = {
        name unique:true
    }
}

class b {
    String description
}

and in domain class b I want to call class a

import a
class b {
    String description
    static constraints = {
         description unique:'a.name'
    }
}

and get error

Scope for constraint [unique] of property [description] of class [b] must be a valid property name of same class

How do I get a property from class a to b?

Upvotes: 0

Views: 735

Answers (2)

Bart
Bart

Reputation: 17371

Assuming you try to do this in Grails 2+

You can't use validation that way. In your example you need to reference to a property of the same domain class. To correct the constraint in class B you can write:

class B {
    String description
    static contraints = {
        description unique:true
    }
}

But I think you want to import the constraints from class a which is done like this.

class B {
    String description
    static contraints = {
        importFrom A
    }
}

See http://grails.org/doc/latest/guide/validation.html#sharingConstraints

This will import all constraints on properties that the two classes share. Which in your case is none.


UPDATE

I got a similar question and found a solution for it. So I thought to share it here with you. The problem can be solved with a custom validator. In your case constraints for class B:

static constraints = {

    description(validator: {
        if (!it) {
            // validates to TRUE if the collection is empty
            // prevents NULL exception
            return true
        }

        def names = A.findAll()*.name
        return names == names.unique()
    })
}

It's difficult to answer your question correctly since the requirements are a bit odd. But maybe it will help.

Upvotes: 1

doelleri
doelleri

Reputation: 19702

You need to write a custom validator to check the uniqueness since it relies on more information than the single instance of b will have.

Something like

static constraints {
     description validator: { val ->
         !a.findByName(val)
     }
}

might do the trick.

Upvotes: 1

Related Questions