user3256520
user3256520

Reputation: 451

multiple condition checks on grails domain constraints?

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() == 0then 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

Answers (1)

Paweł Piecyk
Paweł Piecyk

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

Related Questions