Reputation: 11915
Is it possible to write your own validator in grails that will return a valid object?
Something like:
static constraints = {
name(validator: {val, obj ->
if (Drink.findByName(val)) return [Drink.findByName(val)]
})
}
In other words - if the Drink already exists in the DB, just return the existing one when someone does a
new Drink("Coke")
and coke is already in the database
Upvotes: 1
Views: 978
Reputation: 412
Not sure if you can do this from inside the validator, but:
Drink d = Drink.findOrSaveWhere(name: 'Smooth Drink', alcoholLevel: '4.5')
Upvotes: 0
Reputation: 120286
You cannot do this with a custom validator. It's not really what it was meant for. From the Grails Reference:
The closure can return:
null
or true
to indicate that the value is validfalse
to indicate an invalid value and use the default message codegrails-app/i18n/message.properties
to see how the default error message codes use the arguments.An alternative might be to just create a service method that 1) looks for the domain and returns it if it exists, 2) otherwise, saves the domain and returns it.
There's probably a more elegant alternative. Regardless, Grails' constraints mechanism isn't (and shouldn't be) capable of this.
Upvotes: 2