Enum values as dropdown list
Asked Answered
U

2

6

I am facing an issue populating a dropdown list from Enum class values. My enum class code is:

package abc.xyz.constants;

public enum StateConstantsEnum
{
           NEWYORK("NY"), 
            FLORIDA("FL"), 
            CALIFORNIA("CA"), 

    private String fullState;

    private StateConstantsEnum( String s )
    {
        fullState = s;
    }

    public String getState()
    {
        return fullState;
    }
}

I want populate dropdown list with NEWYORK, FLORIDA and CALIFORNIA. I am creating and adding the list to Spring model this way:

List<StateConstantsEnum> stateList = new ArrayList<StateConstantsEnum>( Arrays.asList(StateConstantsEnum.values() ));

model.addAttribute("stateList", stateList);

Then I am trying to populate the dropdown in JSP using:

<select name="${status.expression}" name="stateLst" id="stateLst">
    <option value=""></option>
        <c:forEach items="${stateList}" var="option">
                <option value="${option}">
                    <c:out value="${option.fullState}"></c:out>
                </option>
        </c:forEach>
</select>

But I am getting an exception "Exception created : javax.el.PropertyNotFoundException: The class 'abc.xyz.constants.StateConstantsEnum' does not have the property 'fullState'."

How do I fix this problem? Help much appreciated

Underpants answered 29/9, 2011 at 2:23 Comment(0)
H
7

fullState is private, getState() is the accessor.

<c:out value="${option.state}"></c:out>

Or rename your getter to getFullstate().

Heidyheifer answered 29/9, 2011 at 2:25 Comment(4)
I think <c:out value="${option.state}"></c:out> would be correct.Magdala
Oops.. I missed out on a small piece. Thanks. One more problem, this is printing NY, FL, CA, not NEWYORK, FLORIDA and CALIFORNIA. Any idea?Underpants
Just use ${option} then. Actually, the "fullstate" name is misleading. It's the other way round. It holds a state abbreviation.Roundworm
Thanks for the help and suggestion BalusC. I'll change it.Underpants
W
0

in your JSP you can use a like that :

<form:select path="*">
  <form:options items="${stateList}" itemLabel="fullState"  />
</form:select>

it will extract all element in your liste (stateList) and if you dont specify an itemLabel and itemValue, it'll take your enums values of course you have to set your getter to getFullState,and declare springmvc tags in your page

Warehouse answered 13/6, 2013 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.