Queequeg
Queequeg

Reputation: 2864

How does Grails convert String to Enum?

I have a custom toString method in my enum:

enum TaxRate implements Serializable {
    RATE23(23.0),
    ...

    private String s
    private BigDecimal rate

    private TaxRate(BigDecimal s) {
        this.s = s + "%"
        this.rate = s * 0.01
    }

    public String toString() {
        return s
    }

Now when I display the rates in HTML I get nice output like TAX: 23.0%.

But what happens when a user selects the tax from a <select> and the sent value is i.e. 23.0% is that Grails can't create/get the TaxRate instance...

What should I override to support this custom mapping? Trying to override valueOf(String) ended with a error..

Upvotes: 4

Views: 3907

Answers (1)

tim_yates
tim_yates

Reputation: 171084

Have you seen the entry at the bottom of this page?

If you want to use a Enum with a "value" String attribute (a pretty common idiom) in a element, try this:

enum Rating {
    G("G"),PG("PG"),PG13("PG-13"),R("R"),NC17("NC-17"),NR("Not Rated")

    final String value

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

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

Then add optionKey="key" to your tag.

Upvotes: 6

Related Questions