How does Grails convert String to Enum?

I have my own toString method in my enumeration:

 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 show bids in HTML, I get a good result, for example TAX: 23.0%.

But what happens when a user selects a tax with <select> , and the value sent is ie 23.0% - this is what Grails cannot create / get an instance of TaxRate ...

What should I override to support this custom mapping? An attempt to override valueOf(String) failed.

+4
source share
1 answer

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

If you want to use Enum with the String attribute "value" (a fairly common idiom) in an element, try the following:

 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.

+6
source

Source: https://habr.com/ru/post/1397791/


All Articles