Reputation: 49
Hello
I need to perform Domain class filtering in Groovy for provided filter fields. Here is code sample:
User.findAll(name: filter.name, age: filter.age, department: filter.department)
Is there exists some syntax sugar to help me to validate if for example filter.name is not provided e.g. null or empty - do not filter by this field. Thanks.
Upvotes: 0
Views: 337
Reputation: 20699
you can apply the sugar right on the arguments map (assuming filter is a Map):
def args = filter.collectEntries{ k, v ->
[ 'age', 'name', 'department' ].contains( k ) && v ? [ (k):v ] : Collections.EMPTY_MAP
}
def users = User.findAll args
Upvotes: 0
Reputation: 148
Abs has right. Here is an example with if-statements for not provided filter fields:
User.createCriteria().list {
if (filter.name) eq("name", filter.name)
if (filter.age) eq("age", filter.age)
if (filter.department) eq("department", filter.department)
}
Upvotes: 2