Reputation: 1783
I have a method that looks like this
def searchInAllField(String searchString) {
Long companyId = sessionService.userProfile.companyId;
return Vendor.createCriteria().list(){
eq("companyId", companyId);
if (searchString) {
or {
ilike("name", "%${searchString}%")
ilike("businessName", "%${searchString}%")
ilike("address", "%${searchString}%")
ilike("description", "%${searchString}%")
ilike("contactPerson", "%${searchString}%")
ilike("mobileNumber", "%${searchString}%")
ilike("officeNumber", "%${searchString}%")
ilike("email", "%${searchString}%")
}
}
order("businessName", "asc");
} ?: [];
}
This method accepts searchString parameter and check if it matches the value in all field.
The result of this method is a list which needs to be displayed and put a pagination. How can I put a grails pagination if I already have the list?
Upvotes: 0
Views: 31
Reputation: 9885
To use pagination your searchInAllField()
method needs to incorporate max
and offset
parameters.
def searchInAllField(String searchString, int max, int offset) {
Long companyId = sessionService.userProfile.companyId;
return Vendor.createCriteria().list(max: max, offset: offset) {
eq("companyId", companyId);
if (searchString) {
or {
ilike("name", "%${searchString}%")
ilike("businessName", "%${searchString}%")
ilike("address", "%${searchString}%")
ilike("description", "%${searchString}%")
ilike("contactPerson", "%${searchString}%")
ilike("mobileNumber", "%${searchString}%")
ilike("officeNumber", "%${searchString}%")
ilike("email", "%${searchString}%")
}
}
order("businessName", "asc")
}
}
The controller method which calls searchInAllField()
will need to pass max
and offset
along and provide a total count in the model:
def someControllerMethod() {
def vendors = whatever.searchInAllField(searchString, params.max, params.offset)
render(model: [vendors: vendors, totalVendors: vendors.totalCount])
}
The total count, in this case vendors.totalCount
, is important. The g:paginate
taglib needs this to function correctly.
Note: The g:paginate documentation can mislead you. It demonstrates using DomainClass.count()
as the total count. What you want is the query result count not the total number of records in the database table. The totalCount
property provides what you need, but you only get the property when you execute the query with offset
and max
.
Finally, you can use the g:paginate
taglib in your GSP code to render the pagination links:
<g:paginate controller="someController" action="someControllerMethod" total="${totalVendors}" />
Upvotes: 1