Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reuse Criteria in Grails Controller

typically you have the following last line in a Grails generated Controller list method:

[userInstanceList: User.list(params), userInstanceTotal: User.count()]

if I want to restrict the users by a specific criteria it looks like

[userInstanceList: User.list(params) {
   ilike('login', '%test%')
 }, userInstanceTotal: User.count() {
   ilike('login', '%test%')
 }]

but this violates the DRY principle - what would be the best way to reuse the criteria closure?

like image 509
Thomas Einwaller Avatar asked Dec 21 '22 17:12

Thomas Einwaller


1 Answers

Paged results from a criteria builder (the result class is PagedResultList) have a property, totalCount, which you can use just like you were calling count() on the same criteria:

def userInstanceList = User.createCriteria().list(params) {
    ilike 'login', '%test%'
}
[userInstanceList: userInstanceList, userInstanceTotal: userInstanceList.totalCount]
like image 160
Dana Avatar answered Jan 08 '23 01:01

Dana