Override the toString method in Grails

The Grails framework is pretty smart in that if you have objects that are related to another object, it will allow you to associate an object at creation time. For example, if you had an User class, which had a “hasMany” relationship with the Post class, when creating a new Post object you would see a drop down allowing you to select a User:

Note that this is assuming that you’ve used the “generate-all” command to create the default scaffolding. The screen listing the Posts also shows the User:

However, as we can see from the above screenshot the values in the drop down and the User field don’t seem to make much sense. The reason for the values are that by default the scaffolding generator calls the “toString” method on the object. Which is set to return the class name of the object, plus it’s unique id. While this makes sense to have as the default, we need to change it in order to make it easier for people to read.

Fortunately, changing it is quite straightforward, with us only needing to define (override) the toString method. Simply add the following to the User domain class:

String toString(){
  return username
}

After putting this into the User controller, restart the grails application and you should see the usernames of the users in the drop down when creating a new Post:

This works for any class that you can think of. Simply override the toString method to make it more presentable to the people using the site. I do this almost automatically for all of my domain classes.

3 Replies to “Override the toString method in Grails”

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.