DEV Community

Joe McCall
Joe McCall

Posted on • Originally published at joemccall86.gitlab.com on

Grails Views - Rendering Empty Lists

Do you have a controller action that looks like this?

def index() {
  respond myService.listItems()
}

Enter fullscreen mode Exit fullscreen mode

Does that controller show a view like this?

model {
  List<Item> itemList
}

json g.render(itemList)

Enter fullscreen mode Exit fullscreen mode

This may appear to work fine when itemList is populated, but you may notice that the API is broken when the index method is run when there are no items in the list:

$ curl http://localhost:8080/api/items
[
   null
]

Enter fullscreen mode Exit fullscreen mode

What? This is supposed to render [] because we’re responding with an empty list. What happened?

Let’s look at this from the documentation found here: http://views.grails.org/latest/

If the collection is empty, emptyCollection will be used as the default model name. This is due to not being able to inspect the first object’s type.

So the itemList field on our model is null because the auto model-binding computes to emptyCollection. There are technical reasons for this. The fastest way to fix this is to change how we call respond:

def index() {
  respond([itemList: myService.listItems()])
}

Enter fullscreen mode Exit fullscreen mode

This forces the itemList in the model to be bound manually, whether it is empty or not.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay