tags:

views:

278

answers:

1
+3  A: 

I don't know if this is the best approach, but you could have an enum to do the work:

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
    }
}

Add an instance of the SelectOptions enum to your domain:

class MyDomain {
    SelectOptions selectOptions = SelectOptions.ACTIVE
    //Other properties go here

    static constraints = {
        selectOptions(inList:SelectOptions.list())
        //other constraints
    }
}

Then in your GSP view:

<g:select
    name="status"
    from="${myDomainInstance.constraints.selectOptions.inList}"
    value="${myDomainInstance.selectOptions}" />

In your controller's save method, you need to get the correct enum from the String value submitted by the view:

def save = {
    SelectOptions selectOption = SelectOptions.getByName(params.status)
    def myDomainInstance = new MyDomain(params)
    myDomainInstance.selectOptions = selectOption
    // proceed to save your domain instance
}
Cesar
Thanks Cesar for your reply, however when I click create I get the following error Failed to convert property value of type java.lang.String to required type com.myCompany.SelectOptions for property status; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.myCompany.SelectOptions] for property status: no matching editors or conversion strategy found
WaZ
Yes, the problem basically is that from the GSP you submit a String, but the domain object expects an enum. I edited my answer to reflect that.
Cesar