validationgrailsgroovygrails-ormdomain-object

Grails Domain: How to access parent domain data?


I have a parent child domain structure, and I want access parent domain data in child domain for validator. For example in the code example below, child1 has a variable 'name' and for validator purpose I need child2 data.

How can I achieve this situation?

I have domain structure like this:

class Parent{
    Child child1
    Child child2

    static mapping = {
        child1 lazy:false
        child2 lazy:false
    }
}

class Child{
    String name
    // some other variables

    static belongsTo = [parent:Parent]

    static constraints = {
        name(nullable:true,validator:{val, obj ->
            if(obj.parent){
                return true
            }
            return false
        })
    }
}

I tried this.parent.child2 but parent is found null.

EDIT:
Changed:
static belongsTo = [parent:Parent]

Also added in validator:
if(obj.parent){ return true } return false

Still it is returning false.


Solution

  • Replace

    static belongsTo = [Parent]
    

    with

    static belongsTo = [parent: Parent]
    

    so the child know its parent