我发现人们已尝试将多个复选框绑定到单个字段,但未能将其绑定。这是我的例子..有没有更多的常规方法来做到这一点?
index.gsp中
<html>
<head>
<meta name="layout" content="main"/>
<title>Dat multiple check box to string tho</title>
</head>
<body>
<g:form action="submitFormIndex">
Applicant Name<g:textField name="name" required="" value=""/>
<br>
Albany: <g:checkBox name="albany" value="albany" checked="false" /> <br>
Allegany: <g:checkBox name="allegany" value="allegany" checked="false" /> <br>
Bronx: <g:checkBox name="bronx" value="bronx" checked="false" /> <br>
Broome: <g:checkBox name="broome" value="broome" checked="false" /> <br>
Cattaraugus: <g:checkBox name="cattaraugus" value="cattaraugus" checked="false" /> <br>
Cayuga: <g:checkBox name="cayuga" value="cayuga" checked="false" /> <br>
Chautauqua: <g:checkBox name="chautauqua" value="chautauqua" checked="false" /> <br>
Chemung: <g:checkBox name="chemung" value="chemung" checked="false" /> <br>
Chenango: <g:checkBox name="chenango" value="chenango" checked="false" /> <br>
Clinton: <g:checkBox name="clinton" value="clinton" checked="false" /> <br>
Onondaga: <g:checkBox name="onondaga" value="onondaga" checked="false" /> <br> <br>
<g:submitButton name="Submit"/>
</g:form>
</body>
</html>
TestFormController.groovy
package countiesselectme
class TestFormController {
def index() {}
def submitFormIndex(String name, String albany, String allegany, String bronx, String broome, String cattaraugus, String cayuga, String chautauqua, String chemung, String chenango, String clinton, String onondaga) {
def cleanDemNulls = (["${albany}", "${allegany}", "${bronx}", "${broome}", "${cattaraugus}", "${cayuga}", "${chautauqua}", "${chemung}", "${chenango}", "${clinton}", "${onondaga}"]- 'null')
new Applicant(name:"${name}" , countiesWillingToWork:cleanDemNulls).save()
redirect (controller: "Applicant" , action:'index')
}
}
答案 0 :(得分:4)
您可以使用command object或params object来检索复选框值。
%{-- Value can be some gsp boolean var, this example uses constants --}%
<g:checkbox name="albany" value="${true}"/>
<g:checkbox name="allegany" value="${false}"/>
@Validateable
def TestFormCommand {
Boolean albany
Boolean allegany
...
def countiesList(){
def counties = []
if(albany) counties << "albany"
if(allegany) counties << "aalleganybany"
...
return counties
}
}
def action(TestFormCommand cmd){
// Using command object
def albany = cmd.albany
def allegany = cmd.allegany
// Using params
def albanyParam = params.boolean('albany');
def alleganyParam = params.boolean('allegany');
// Use the utility method in the command object
def countiesWillingToWork = cmd.countiesList
...
}
这也意味着您不需要像当前代码中那样删除空值。
正如Giannis在评论中所说,multi-select对于这类数据可能更好。
<g:select from="${counties}" name="counties" multiple="${true}"/>
然后,您可以使用Set<String> counties
将此绑定在命令对象中,或使用params.list('counties')
从params中将其绑定。