Reputation: 13811
I have a domain three domain class like this :
Tasks.groovy
class Tasks {
static belongsTo = [ user : User ]
//other fields
Date startDate
Date endDate
}
User.groovy
class User {
//relationships. . . .
static belongsTo = [ company : Company, role : Role, resource : Resource]
static hasMany = [ holidays : Holiday, tasks : Tasks]
//other fields
}
Holiday.groovy
class Holiday {
static belongsTo = User
Date startDate
Date endDate
//other fields
}
Now when I create a Tasks
instance, I want to put a constraint such that the Tasks
startDate
and endDate
doesn't fall within the User
's Holiday
s startDate
and endDate
. And throw and error if it has.
I want a way to put this constraint on my domain class itself(i.e on Tasks
).
Is it possible to do so?
Thanks in advance.
Upvotes: 2
Views: 375
Reputation: 3047
You can accomplish this using a custom validator.
startDate(validator: {val, obj->
obj.user.holidays.every{holiday-> val <= holiday.startDate || val >= holiday.endDate }
})
You can encapsulate your custom validation logic as a closure. You will have to add similar logic for endDate as well.
Upvotes: 2
Reputation: 1575
I would go with having a createTask
function in the User domain, since Task should not be fiddling with variables that are so far removed (self -> User -> Holiday -> startDate).
It is quite clear that the User knows when its holiday starts and ends and thus would easily validate the given start and end dates for a new Task.
Upvotes: 0