简体   繁体   中英

input component inside ui:repeat, how to save submitted values

I'm displaying a list of questions from database and for each question I have to display a list of options, in this case radio buttons.

<ui:repeat value="#{formData.questions}" var="question">
    <div>
        <p:outputLabel value="#{question.name}" />
        <p:selectOneRadio value="#{formData.selectedOption}">
            <f:selectItems value="#{formData.options}" />
        </p:selectOneRadio>
    </div>
</ui:repeat>

I need to save the checked option for each question.

How can I do this?

You need to associate the input value with the repeated variable var in some way. Right now you're not doing that anywhere and basically binding all input values to one and same bean property. So, when the form gets submitted, every iteration will override the bean property everytime with the value of the current iteration round until you end up getting the value of the last iteration round. This is definitely not right.

The simplest way would be to directly associate it with the object represented by var :

<p:selectOneRadio value="#{question.selectedOption}">

In your specific case, this only tight-couples the "question" model with the "answer" model. It's reasonable to keep them separated. A more proper solution in your specific case is to map it with currently iterated #{question} as key (provided that it has a proper equals() and hashCode() implementation, obviously):

<p:selectOneRadio value="#{formData.selectedOptions[question]}">

With:

private Map<Question, String> selectedOptions = new HashMap<>();

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

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