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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More