Grails的:

时间:2010-03-25 16:42:32

标签: grails

如何实现以下目标:

我的域中存有一个布尔值,默认情况下Grails创建一个复选框作为控件。我想要一个具有值的选择控件:Active / Inactive。 在选择Active时,应传递值True 和 选择InActive后,应传递值False

我怎样才能实现这一目标

<g:select name="status" from="" optionKey="" value=""  />

非常感谢。

2 个答案:

答案 0 :(得分:8)

我不知道这是否是最好的方法,但你可以有一个枚举来完成这项工作:

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
}

答案 1 :(得分:0)

好的经过大量的头脑风暴,我可以搞清楚

我的代码更简单,就像这样:

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>

享受编码

相关问题