jai
jai

Reputation: 21897

how to check if a parameter exists in params?

for ( boldParam in [para1, para2, para2, para4, para5] ) {
    if(/* boldParam exists in params */)
        ilike(boldParam,'%' + params.boldParam + '%')
    }
}

I would like to write something like above. I'm trying to avoid the following multiple if statements:

if (params.para1)
     ilike('para1','%' + params.para1+ '%')
if (params.para2)
     ilike('para2','%' +params.para2+ '%')
if (params.para3)
     ilike('para3','%' + params.para3+ '%')

Upvotes: 7

Views: 15985

Answers (3)

victorf
victorf

Reputation: 1048

An alternative used by me:

['param1','param2','param3','param4','param5'] /* and it also could come from a service */
.each {
    if (params["${it}"]) filters["${it}"] = params["${it}"] 
} /* Do it in your controller and then send $filters to your service */

Upvotes: 0

Daniel Harcek
Daniel Harcek

Reputation: 329

Trying to retrieve property that does not exist will give you null. That means you can simply do

if (!params.missing) {
   println("missing parameter is not present within request.")
}

In different use case you could also give a try to safe dereference operator ?.. For example:

params.email?.encodeAsHTML()

Upvotes: 6

Burt Beckwith
Burt Beckwith

Reputation: 75681

params is a Map, so you can use containsKey():

for (boldParam in [para1, para2, para2, para4, para5]) {
   if (params.containsKey(boldParam)) {
      ilike(boldParam, '%' + params.boldParam + '%')
   }
}

Upvotes: 20

Related Questions