Reputation: 451
For a domain such as
class Question {
String questionText
Type questionType
static hasMany = [choices: Option]
}
I was wondering if this type of conditional constraint is possible. I want the constraint to be such that if the questionType
is either (radio, checkbox, dropdown) and (&&) choices.size() == 0
then constraint is violated and error is thrown. I know the second part of the condition i.e. to check size of collection can be done with size parameter but I was wondering if we can have complex conditions like above i.e. multiple conditions checks with && operators.
Upvotes: 0
Views: 318
Reputation: 2789
So you need custom validator. Something like below should do the job. Take a look at Grails documentation - it's quite convenient.
static constraints = {
questionType validator: { val, obj ->
!(val in [Type.Radio, Type.Checkbox, Type.Dropdown] && obj.choices.isEmpty())
}
}
But then you'll get error message generated by grails. It's good to provide more readable validation error. You can return custom message code and define it in messages.properties
:
static constraints = {
questionType validator: { val, obj ->
if (val in [Type.Radio, Type.Checkbox, Type.Dropdown] && obj.choices.isEmpty())
return 'emptyChoicesErrorMessage'
}
}
Upvotes: 2