问题
I'm new to Grails and obviously missing something out.. but what?!
I created a DomainClass An with a String property category. In the constraints I defined, that this category should have multiple (list) values:
class An {
String category
static constraints = {
category nullable: true, inList:["do", "me", "a", "favour"]
}
}
In the view it is shown as a multiple select box:
<g:select name="category" from="${anInstance.constraints.category.inList}"
value="${anInstance?.category}"
valueMessagePrefix="a.category"
noSelection="${['': 'Please select one ...'}"
multiple="multiple" size="5"/>
The save method is standard:
def save = {
def anInstance = new An(params)
if (anInstance.save(flush: true)){
flash.message = "${message(..)}"
redirect(action: "show", id: anInstance.id)
} else {
render(view: "create", model: [anInstance: anInstance])
}
}
When I select/save just one value, it is selected/shown/saved as expected. When I want to select/save many values from this list, I got the message that the seleced values are not in the list (default.not.inlist.message):
Property [category] of class [class An] with value [do, me, a, favour] is not contained within the list [[do, me, a, favour]].
Any hint is appreciated.
EDIT:
As Mr.Cat pointed out, one of my mistakes was to define the category property as String
and not List<String>
. Now the selected values are shown as selected, but the error message (default.not.inlist.message) still remains.
回答1:
selecting multiple items in select box causes that in the controller you get a list of strings, and then you are trying to store this list in a single String field which is obviously wrong, and specifically doesnt pass your costraint
回答2:
Switch your constraint from
category nullable: true, inList:["do", "me", "a", "favour"]
to
category nullable: true, inList: (["do", "me", "a", "favour"].subsequences() as List)
This will generate the following which should cover all your bases:
[[do, me, a, favour], [a, favour], [a], [me, a, favour], [do, a], [do, me, a], [do, a, favour], [me], [favour], [do, me, favour], [do, me], [me, favour], [do], [me, a], [do, favour]]
来源:https://stackoverflow.com/questions/22013536/how-can-i-select-multiple-values-from-the-inlist-constraint-in-grails