grailsdrop-down-menuenumskey

In Grails g:select, using an enum, display the enum keys, but use the values as the options' values


I wanted to use a g:select tag to produce a select box where the keys of the enum are displayed to the user, while the values of the enum are passed when the form is submitted, using the following enum:

public enum LetterRange {
    ABCD("a-d"),
    EFGH("e-h"),
    IJKLM("i-m"),

    final String value

    AccessLevel(String value) { this.value = value }

    String toString() { value }
    String getKey() { name() }
}

Solution

  • I used the LetterRange enum:

    public enum LetterRange {
        ABCD("a-d"),
        EFGH("e-h"),
        IJKLM("i-m"),
    
        final String value
    
        AccessLevel(String value) { this.value = value }
    
        String toString() { value }
        String getKey() { name() }
    }
    

    ...like so in the 'g:select' tag:

    <g:select id="letterRange" name="letterRange" from="${LetterRange}" 
            noSelection="['':'Select Range...']" optionValue="key" required=""/>
    

    ...which produced the following HTML on the page:

    <select id="batchRange" name="batchRange">
        <option value="a-d">ABCD</option>
        <option value="e-h">EFGH</option>
        <option value="i-m">IJKLM</option>
    </select>