Show enum values on GSP page and then bind them in the database

Nikhil Sharma picture Nikhil Sharma · Jul 29, 2011 · Viewed 12.1k times · Source

I have a use case in which I need to first show the value of enum on the GSP page first as a drop down list, have the user select one of those values and then finally bind the data to the domain.

So my code on GSP looks like my enum is MyEnum

<g:select from="${MyEnum.getAllEnumList()}" optionValue="name" name="duration"/>

my enum is

public enum MyEnum {

    MIN15('15 Minutes'),
    MIN30('30 Minutes'),
    HOUR1('1 Hour'),
    HOUR2('2 Hours'),
    HOUR5('5 Hours'),
    HOUR8('8 Hours'),
    HALFDAY('half day'),
    FULLDAY('full day')

    private final String name
    private final String displayName

    public static final List<MyEnum> getAllEnumList() {
        [MIN15,MIN30,HOUR1,HOUR2,HOUR5,HOUR8,HALFDAY,FULLDAY]
    }

    public String toString() {
        return displayName
    }

    MyEnum(String name,String displayName) {
        this.name = name
        this.displayName = displayName;
    }

}

when I hit the page its showing an error like:

Error processing GroovyPageView: Error executing tag <g:form>: Error evaluating expression [MyEnum.getAllEnumList()] on line [37]: java.lang.NoClassDefFoundError: Could not initialize class ENUM.MyEnum at D:/myspace/projects/IcepushpluginSampleApp/grails-app/views/util/test.gsp:46

Any ideas ????

Answer

Nick Larson picture Nick Larson · Aug 2, 2011

This is how I have done it in the past. This way you have i18n support.

gsp

<g:select name="duration" from="${MyEnum.values()}" valueMessagePrefix="ENUM.MyEnum" />

messages.properties

ENUM.MyEnum.MIN15=15 Minutes
ENUM.MyEnum.MIN30=30 Minutes
ENUM.MyEnum.HOUR1=1 Hour
ENUM.MyEnum.HOUR2=2 Hours
ENUM.MyEnum.HOUR5=5 Hours
ENUM.MyEnum.HOUR8=8 Hours
ENUM.MyEnum.HALFDAY=half day
ENUM.MyEnum.FULLDAY=full day