Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: <g:select

Tags:

grails

How can I achieve the following:

I have a boolean stored in my Domain, by default Grails creates a checkbox as a control. I want a select control with values : Active/Inactive. On selecting Active the value True should be passed and On selecting InActive the value False should be passed.

How can I achieve this using

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

Much appreciated.

like image 988
WaZ Avatar asked Feb 28 '23 07:02

WaZ


1 Answers

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
}
like image 79
Cesar Avatar answered Mar 06 '23 16:03

Cesar