I have a domain object category with a hasMany relation to a domain object attributes
class Category {
Collection<Attribute> attributes = []
static hasMany = [attributes:Attribute]
I use scaffolding to generate a multi select box (different from a quite similar issue mentioned in this question ):
class CategoryController {
static scaffold = true
}
This gets rendered for the view as a select box such as this:
<select id="attributes" class="many-to-many" size="5" multiple="multiple" name="attributes">
<option value="1">entry 1</option>
<option value="2">entry 2</option>
</select>
When not selecting any entries from the select box, nothing gets submitted when sending the form. Thus, de-selecting of all entries in the select box does not get stored but instead all values that had been stored before remain so.
I tried adding an own beforeValidate
method (see below, similar to the solution described in a reply to the question mentioned above ) to my CategoryController but because of scaffolding it doesn't get executed (unless I'm mistaken and there's another reason):
def beforeValidate() {
def categoryInstance = Category .get(params.id)
if (!categoryInstance ) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'categoryInstance.label', default: 'Category'), params.id])
redirect(action: "list")
return
}
if (!(params?.attributes)) {
categoryInstance.attributes.clear()
}
}
I'm at a loss as to what to do now. Forego scaffolding for this controller and use my own beforeValidate
method? Keep scaffolding and implement the method somewhere else? Do something else?
After reading on several websites that grails' scaffolding is only intended to provide a rough outline that one needs to fill to attain more finegrained behaviour, I settled on foregoing scaffolding and created my own controllers and views, then adapted them by modifying their update methods. For future visitors to this question, here's how to create controllers and views: https://grails.github.io/grails-doc/latest/ref/Command%20Line/generate-all.html