2

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 Holidays 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.

Ant's
  • 13,545
  • 27
  • 98
  • 148

2 Answers2

2

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.

Anuj Arora
  • 3,017
  • 3
  • 29
  • 43
  • 2
    Nice! It would probably be better to encapsulate some of that logic into the User class, so the code becomes more clear and respects the Law of Demeter. Something like `startDate(validator: { startDate, self -> self.user.canStartTaskAt(startDate) })` :) – epidemian Feb 24 '12 at 13:27
0

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.

Jan Wikholm
  • 1,557
  • 1
  • 10
  • 19