Tuesday, December 6, 2016

Handling One or Multiple Selection in Grails

Scenario:
We have a select in the form with id="book".
The user may choose none, 1 or multiple in select and submit the form.
There is an each loop in the controller/service to process each user.

What happen:
For each selected book in the select one book=N parameter is posted to the controller.

Grails controller which creates params automatically brings a little intelligence and convert the params to a list if there are multiple instances of that parameters, so in the case of multiple book selection the params will be something like this:

params.book = [ N, M, ...]
It is great and we can loop on it and do the operation on each of them.

But..., if just one user is selected, the there will be no list by default and the param contains just a simple string

params.book = "N"

The bad:

  • The loop is not failed, it is a string and loop iterate over each char of the string
  • In the development and simple test cases, it works perfectly. For example, if it is the id like 5, then it is just a char same as the original. But if the id grows and become something like "58", then your loop process object id 5 and 8.
Solution:
Use params.list method to create a list for that parameter, even if it is single.
def bookIds = params.list("book")

No comments: