zoran119
zoran119

Reputation: 11307

handling multi-select with no selection

I used grails generate-all on my application. The Author view has a multi-select which allows for a number of Book instances:

<g:select multiple="true" ... />

However, if I edit an existing Author who owns 5 out of total 15 books (the multi-select shows 15 books, 5 selected), unselect all books and click save, the Author still keeps their 5 books. From what I can tell, no book input from the form - books property of Author don't get changed.

Now, I can test for this in my controller (something like this):

if (params?.books.size() < 1) {
     authorInstance.books = []
}

Is this the way to do it, or is there a better way?

Upvotes: 2

Views: 871

Answers (2)

Nico O
Nico O

Reputation: 14132

I had the same problem, that a multi select list can not be emptied by default data binding, as the params map does not contain fields with a value of NULL.

To circumvent this, you can do this in your .gsp:

<g:hiddenField name="books" value="" />
<g:select multiple="true" name="books" />

When you post this form elements, the multi select will override the hidden field. If the multi select is empty, you will fallback to the empty string.

Not pretty, but get the job done, when you can not alter the controller action.

Upvotes: 0

Rob Hruska
Rob Hruska

Reputation: 120346

Most examples I've seen use:

authorInstance.books.clear()

Upvotes: 3

Related Questions