I'm trying to setup an dynamic SearchService in Grails 2.4.3 to use it for all domain Class searches.
Now I'm coming to the problem to resolve the given sort property that are not in the class where the Criteria is on.
For Example:
I have an Foo
Class which contains an property Bar bar
and Bar has the property String name
. Now I want to sort after the name of Bar, so I'm getting in the Service bar.name
as sort parameter.
Now I must dynamically resolve this sort parameter that I can also use something like world.name
.
I found this :
def criteria = Child.createCriteria();
println criteria.list{
parent {
order("name")
}
}
I tried to make it dynamic, here is a part of my method:
def c = domainClass.createCriteria()
def list = c.listDistinct {
if (sort) {
if (sort.contains('.')) {
String[] splittedSort = sort.tokenize('.')
sort = splittedSort.last()
splittedSort = splittedSort[0..-2]
splittedSort[0].toString() {
order(sort, sortorder)
}
} else {
order(sort, sortorder)
}
}
}
This does not work :(
Any Suggestions how I can get this work?
Instead of trying to call a method via a dynamic name, you can use a criteria query alias. Like this:
def c = domainClass.createCriteria()
def list = c.listDistinct {
if (sort) {
if (sort.contains('.')) {
String[] splittedSort = sort.tokenize('.')
sort = splittedSort.last()
splittedSort = splittedSort[0..-2]
createAlias(splittedSort.join('.'), 'sortAlias')
order("sortAlias.${sort}", sortorder)
} else {
order(sort, sortorder)
}
}
}