How can I select multiple values from the inList constraint in Grails?

非 Y 不嫁゛ 提交于 2019-12-13 04:04:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!