Converting param values in Grails

There are some cases in Grails where you want to compare values as Integers instead of the default String objects. There are two ways to do this. The first is to use either the “parseInt” or “valueOf” methods which are original Java methods. The other way to skin this cat is to call the “int()” method on the params object:

if(Integer.parseInt(params.user.id) != user.id){

}
if(params.int(‘user.id’) != user.id){

}

There are other methods which the params object has to easily convert HTTP post values to well known data types, such as:

param.short(…)
param.byte(…)
param.long(…)
param.double(…)
param.boolean(…)

Another nice feature is that these methods accept a second optional parameter, which is the default that the value is set to, in the case that there is an error in the conversion:

def price = prams.float(“seventy”, 0.0)

This behaviour is documented in the Grails documentation here. Although, there doesn’t seem to be a comprehensive list of the methods available at the time of writing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.