2

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Jones
  • 1,036
  • 5
  • 20
  • 37
  • What does not work with this? (Depending upon your need, you can optionally use other iterating components such as especially in this case, [``](http://www.primefaces.org/showcase/ui/data/dataList.xhtml). As a bonus, you will receive a pagination facility out of the box, if the list holing questions is too long). – Tiny Jan 20 '15 at 20:49

1 Answers1

5

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I am using map approach, so what is the right place to clear the map? second thing I am using session scope managed bean for exam is this correct? and lastly I just need to know what is the right way to pass the jpa Entity object to the JSF page? – eatSleepCode Oct 08 '15 at 11:37
  • Thanks it helped! can you please share some thoughts over what is the good practice for JPA entity into jsf layer? – eatSleepCode Oct 08 '15 at 12:24
  • @eatSleepCode: http://stackoverflow.com/q/30639785 If you want more links, look at https://jsf.zeef.com/bauke.scholtz – BalusC Oct 08 '15 at 12:29