简体   繁体   中英

SelectOneMenu's value is always 0 in the backing bean

I have a problem with getting the selected value.

It is always 0.

XHTML file:

<p:selectOneMenu id="SelectDicimalsInput5" value="#{auction.money}">
    <f:selectItem itemLabel="1" itemValue="1"/>
    <f:selectItem itemLabel="5" itemValue="5"/>
    <f:selectItem itemLabel="10" itemValue="10"/>
    <f:selectItem itemLabel="100" itemValue="100"/>
    <f:selectItem itemLabel="500" itemValue="500"/>
    <f:selectItem itemLabel="1000" itemValue="1000"/>
</p:selectOneMenu>

Backing bean :

@ManagedBean (name="auction")
@RequestScoped
public class AuctionBean implements Serializable {
    private int money;
    //getters & setters ...
}

The problem here is that your selectonemenu selected value is a String and your variable in the backed bean is an int .

So this selected value can't be converted to int and that's why you always get 0 as the defailt value of the primitive type int here.

You have to convert this String into an int to match the variable type, you can use an IntegerConverter :

<f:convertNumber integerOnly="true" />

and your code will be:

<p:selectOneMenu id="SelectDicimalsInput5" value="#{auction.money}">
    <f:selectItem itemLabel="1" itemValue="1"/>
    <f:selectItem itemLabel="5" itemValue="5"/>
    <f:selectItem itemLabel="10" itemValue="10"/>
    <f:selectItem itemLabel="100" itemValue="100"/>
    <f:selectItem itemLabel="500" itemValue="500"/>
    <f:selectItem itemLabel="1000" itemValue="1000"/>
<f:convertNumber integerOnly="true" /> //This converter should be added
</p:selectOneMenu>

Also note that there's the converter="javax.faces.Integer" attribute that can be used with <h:selectOneMenu> elements but I think it's not supported by primefaces, but may be I am wrong, so you can try :

<p:selectOneMenu id="SelectDicimalsInput5" converter="javax.faces.Integer" value="#{auction.money}">

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