简体   繁体   中英

selectOneMenu does not show the proper value but getter gets it

Given this selectOneMenu

<h:selectOneMenu value="#{fb.aktionTxt}">
    <f:selectItems value="#{myBean.FBAEnum}" />
</h:selectOneMenu>

this bean code

public FehlerBewertungAktionEnum[] getFBAEnum() {
        return FehlerBewertungAktionEnum.values();
}

this enum

public enum FehlerBewertungAktionEnum {

    NEKO_NEKO("NEK0-NEK0           "),
    CURSOR_PARAMETER("CURSOR-PARAMETER    "),
    CURSOR_LEER("CURSOR-LEER         ");

    private final String str;
    FehlerBewertungAktionEnum(String str) { this.str = str;}
    public String toString(){ return str; }

}

and a database value of aktionTxt

|CURSOR_LEER         | (20 chars)

why does it display NEK0-NEK0 (first element of the enum) instead of CURSOR_LEER in my selectOneMenu, when the getter returns |CURSOR_LEER | ? I debugged the jsf page and found that no <option> has the selected attribute.

The strange thing also is that I can create a new element with the same jsf code and it will properly save my new object to the DB. I am pretty sure there is no way to use trim() here since then I cannot save my fb object.

NEK0-NEK0 is being selected because it is the first one in the list, and none of the items could be matched by value to #{fb.aktionTxt} . You could add one default item which will be selected in this case.

<h:selectOneMenu value="#{fb.aktionTxt}">
    <f:selectItem itemLabel="Select one..."/>
    <f:selectItems value="#{myBean.FBAEnum}" />
</h:selectOneMenu>

If #{fb.aktionTxt} resolves to (its type is) FehlerBewertungAktionEnum , it should work. But, if it is String then no value from the list would be equal to it because Enum is compared to String , resulting in the first item being selected. In this case, if #{fb.aktionTxt} is String , you could try this for <f:selectItems>

<f:selectItems value="#{myBean.FBAEnum}" var="myEnum" itemLabel="#{myEnum.toString()}" itemValue="#{myEnum.toString()}"/>

Oh - my - god

The database value is |CURSOR_LEER | (20 chars) with an underscore while my enum uses a hyphen . How could neither me, my colleague or anybody reading this not see this for so long >.<

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM