creating dynamic selectOneRadion using a bean

83 views Asked by At

I need to build an app of Quiz that contains questions (each question has 2 possible answers) I stored some questions in database. once you select an answer and click "Next", you'll see the next question. I have a bean that represent each question, it's called Item, and has the attributes: question, ansA, ansB; and I have a bean:

@ManagedBean
@ViewScoped
public class Bean {

private List<Item> items = new ArrayList<Item>();
private List<Item> helper = new ArrayList<Item>();
private String myValue;
int indexHelp = 0;

public String next() {
    items.clear();
    items.add(helper.get(indexHelp));
    indexHelp++;

    System.out.println("chose: " + myValue);

    return "ok";
}

the list helper is stored already with the questions from the database

the jsf file:

<h:form>
        <h:dataTable value="#{bean.items}" var="item">
            <h:selectOneRadio value="#{bean.myValue}">
                <h:column>
                    <f:selectItem itemLabel="#{item.question}"      />
                </h:column>
                <h:column>
                    <f:selectItem itemValue="1" itemLabel="#{item.ansA}" />
                </h:column>
                <h:column>
                    <f:selectItem itemValue="2" itemLabel="#{item.ansB}" />
                </h:column>

            </h:selectOneRadio>
        </h:dataTable>
        <h:commandButton value="Next" action="#{bean.next}" />
    </h:form>

the problem is that when I run the project, it doesn't show the radio buttons, the question or the answers. Thank you!!

1

There are 1 answers

2
mabi On

Here's something that matches your description:

public class Item {
     String question;
     String chosen;
     String ansA;
     String ansB;
}

@ManagedBean
@ViewScoped
public AnswerBean implements Serializable {
     private List<Item> alreadyAnswered = new ArrayList<>();
     private Item nextQuestion;

     @PostConstruct
     public void retrieveNextQuestion() {
         // pull "next" question from DB and assign it to nextQuestion
     }

     public void save() {
         alreadyAnswered.add(nextQuestion);
         retrieveNextQuestion();
     }
}

And your JSF page goes like this:

<h:form>
    <h:outputText value="#{answerBean.nextQuestion.question}" />
    <h:selectOneRadio value="#{answerBean.nextQuestion.chosen}">
        <f:selectItem itemValue="1" itemLabel"#{answerBean.nextQuestion.ansA}" />
        <f:selectItem itemValue="2" itemLabel"#{answerBean.nextQuestion.ansB}" />
    </h:selectOneRadio>
    <h:commandButton action="#{answerBean.save}" value="Next" />
</h:form>

You probably want to add a "evaluate" button that you show when there's no question left or something (since you need to do something with the alreadyAnswered list of questions).