-2

I want to use a selectOneMenu dropdown with Enum values. I get to display the values fine, but I'm not able to pass the selected value back to the bean.

Enum

public enum Color {
    RED("Red"), BLUE("Blue"), GREEN("Green");
    private String label;
    private Color(String label) {
        this.label = label;
    }
    public String getLabel() {
        return label;
    }
}

Bean1

@ManagedBean
@ApplicationScoped
    public class Data {
    public Color[] getColors() {
        return Color.values();
    }
}

Bean2

@ManagedBean(name="bean")
@SessionScoped
    public class TestBean {
    private Color color;

    public Color getColor() {
        return color;
    }
    public void setColor(Color color) {
        this.color = color;
    }   
    public void submit() {
        System.out.println(color.getLabel());
    }
}

xhtml

<h:body>
    <h:form>
        <h:selectOneMenu value="bean.color">
            <f:selectItems value="#{data.colors}" var="color" itemValue="#{color}" itemLabel="#{color.label}"/> 
        </h:selectOneMenu>                             
        <h:commandButton value="Submit" action="#{bean.submit}" />
    </h:form>
    <h:outputText value="#{bean.color}" />
</h:body>

On submit I get a 500 caused by NullPointerException in the submit() function. The problem is bean.color doesn't get initialized with the selected value. I'm sure it's something basic though...

  • Also, I noticed **NO SPACE** between attributed **var** and **itemValue** – www.hybriscx.com Oct 31 '19 at 21:42
  • Thanks, missing space was formatting error in the post here, corrected it. As to it never worked: According to this [thread](https://stackoverflow.com/questions/8229638/how-to-use-enum-values-in-fselectitems#8229982) it should work, no? – rookie_senior Oct 31 '19 at 21:50
  • Aah got it. Apologies as it didn't help. One small thing if it helps... `bean.color` needs to be changed to `#{bean.color}` in `` – www.hybriscx.com Oct 31 '19 at 22:02

1 Answers1

0

bean.color should be changed to #{bean.color} in <h:selectOneMenu value="bean.color">

Could you give it a try please?

www.hybriscx.com
  • 1,129
  • 4
  • 22