Steve Kuo
Steve Kuo

Reputation: 63064

Use Spring options tag to display enum's toString value

I'm using Spring for an HTML form. One of the fields is an enum and thus I'd like a HTML drop-down list (<option> tag). My enum's name is different than the toString() value. For example:

public enum Size {
    SMALL("Small"), LARGE("Large"), VERY_LARGE("Very large");

    private final String displayName;

    private Size(String displayName) {
        this.displayName = displayName;
    }

    public String toString() {
        return displayName;
    }
}

I want the user to see the toString() value. Normally this is accomplished using the itemLabel of the Spring options tag.

<form:options items="${enumValues}" itemLabel="beanProperty" />

But toString() isn't a bean property as it doesn't start with "get". Is there a way to set itemLabel to use toString's value without having to create a getter?

Upvotes: 11

Views: 7037

Answers (3)

user1366265
user1366265

Reputation: 1436

I know this is few years old and must be solved by now, but thought I'd add the solution for future comers.

Just remove the [itemLabel="beanProperty"] part. It will use the toString to print the values.

Upvotes: 6

cdeszaq
cdeszaq

Reputation: 31280

Have you tried using Spring's powerful AOP model to extend your enums from one place? It would seem that, depending on how many enums you have, you could easily add a getDisplayName() method to all of them that simply returns their toString() value.

Upvotes: 1

Jeff Olson
Jeff Olson

Reputation: 6463

Why not add a public getDisplayName() method to your enum?

Upvotes: 2

Related Questions