Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a parameter exists in params?

Tags:

grails

groovy

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+ '%')
like image 803
jai Avatar asked Jun 10 '11 05:06

jai


2 Answers

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 + '%')
   }
}
like image 156
Burt Beckwith Avatar answered Oct 08 '22 20:10

Burt Beckwith


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()
like image 45
Daniel Harcek Avatar answered Oct 08 '22 21:10

Daniel Harcek