Input field in always receives value of last item in list

后端 未结 3 772
终归单人心
终归单人心 2021-01-23 11:23

I have a displaying a product catalog in Proudcts.xhtml:


    

        
3条回答
  •  無奈伤痛
    2021-01-23 11:43

    Here,

    
    

    You're basically binding the value of all input fields to one and same bean property. So, when the form gets submitted, every iteration of the table will override the bean property everytime with the submitted value of the current iteration round until you end up getting the value of the last row. If you have placed a debug breakpoint on the setter method, you should have noticed that.

    This is definitely not right. You need to associate the input value with the currently iterated object. The simplest but naive way would be to directly associate it with the object:

    
    

    This only tight-couples in your particular case the "quantity" model with the "product" model. It's functionally reasonable to keep them separated. A more proper solution is then to map the input value with currently iterated object as key (provided that the object has a proper equals() and hashCode() implementation, obviously):

    
    

    With:

    private Map quantitiesPurchased = new HashMap<>();
    

    Regardless of the approach, in the action method, just iterate over it to collect them all.

提交回复
热议问题