[英]Grails: <g:select
我怎样才能实现以下目标:
我有一个存储在我的域中的布尔值,默认情况下Grails创建一个复选框作为控件。 我想要一个具有值的选择控件:Active / Inactive。 在选择Active
,应传递值True
,在选择InActive
,应传递值False
。
我怎样才能实现这一目标
<g:select name="status" from="" optionKey="" value="" />
非常感激。
我不知道这是否是最好的方法,但你可以有一个枚举来完成这项工作:
public enum SelectOptions{
ACTIVE(true, 'Active'),
INACTIVE(false, 'InActive')
Boolean optionValue
String name
SelectOptions(boolean optionValue, String name){
this.optionValue = optionValue
this.name = name
}
static getByName(String name){
for(SelectOptions so : SelectOptions.values()){
if(so.name.equals(name)){
return so;
}
}
return null;
}
static list(){
[ACTIVE, INACTIVE]
}
public String toString(){
return name
}
}
将SelectOptions枚举的实例添加到您的域:
class MyDomain {
SelectOptions selectOptions = SelectOptions.ACTIVE
//Other properties go here
static constraints = {
selectOptions(inList:SelectOptions.list())
//other constraints
}
}
然后在您的GSP视图中:
<g:select
name="status"
from="${myDomainInstance.constraints.selectOptions.inList}"
value="${myDomainInstance.selectOptions}" />
在控制器的save方法中,您需要从视图提交的String值中获取正确的枚举:
def save = {
SelectOptions selectOption = SelectOptions.getByName(params.status)
def myDomainInstance = new MyDomain(params)
myDomainInstance.selectOptions = selectOption
// proceed to save your domain instance
}
好的经过大量的头脑风暴,我可以搞清楚
我的代码更简单,如下所示:
package exproj.masters
public enum ExamDurationTypes{
FULL_EXAM(1, 'For Whole Exam'),
PER_QUESTION(2, 'Per Question')
Integer optionValue
String name
ExamDurationTypes(Integer optionValue, String name){
this.optionValue = optionValue
this.name = name
}
static getByName(String name){
for(ExamDurationTypes edt : ExamDurationTypes.values()){
if(edt.name.equals(name)){
return edt;
}
}
return null;
}
static list(){
[FULL_EXAM, PER_QUESTION]
}
public String toString(){
return optionValue
}
}
然后我将它添加到我的Domain类
class Exam {
.
.
.
Integer durationType
static constraints = {
durationType(inList: ExamDurationTypes.list())
}
}
在我的GSP页面中,我这样破解了它
<g:select
name="durationType"
from="${exproj.masters.ExamDurationTypes.values()*.getName()}"
keys="${exproj.masters.ExamDurationTypes.values()*.getOptionValue()}"
value="${examInstance.durationType}" />
最后产生这个:
<select name="durationType" id="durationType">
<option value="1">For Whole Exam</option>
<option value="2">Per Question</option>
</select>
享受编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.