ninjasense
ninjasense

Reputation: 13856

How to filter Groovy/Grails closure from web app

I have a web app that makes a call to a grails app for its db calls. The db is filled with products that are returned through groovy calls. An example object that I would get from the db is as follows:

class Product{
    Boolean is_blue;
    Boolean is_round;
    Boolean is_alive;
    Boolean is_active;
    String type;
    String name;
}

I want to make a call to the grails app to filter on these boolean values but I am not sure how to do it via a closure, this what my closure currently looks like.

def productXML = 
     Product.findAll("from Product as p where p.is_active = 1 and p.type = :type 
                      ORDER BY p.${params.sort} ${params.order}", 
                      [type: type], [max: params.max, offset: params.offset])

What I'm most confused on is how I can pass these parameters to the closure. Any help would be greatly appreciated. Thanks.

Upvotes: 1

Views: 242

Answers (3)

ninjasense
ninjasense

Reputation: 13856

I ended up making a query builder where if in in the query string it had is_blue=1, I would add that to the query.

    if(params.is_blue){
        query +=" and p.is_blue = ${params.is_blue}"
    }

Upvotes: 0

Captian Trips
Captian Trips

Reputation: 49

  1. Always use substitution variables
  2. To make parameters optional, use this trick (using type as an example):

def productXML = Product.findAll("from Product as p where p.is_active is :active and (p.type = :type or :type == null) ORDER BY p.:sort :order", [type: type, active: true, sort:params.sort, order:params.order], [max: params.max, offset: params.offset])

Upvotes: 0

dmahapatro
dmahapatro

Reputation: 50275

Something like

def productXML = 
     Product.findAll("from Product as p where p.is_active is :active \
                      and p.type = :type \
                      ORDER BY p.${params.sort} ${params.order}", 
                      [type: type, active: true], 
                      [max: params.max, offset: params.offset])

OR

def productXML = Product.findAll(params){
    type == type && is_active == active
}

is what you are looking for? Refer findAll for details.

Upvotes: 1

Related Questions