How to insert data from inpuText into a list using JSF?

4

I have the following problem:

I need a form to submit test questions. Therefore, the form should contain a field for the question (question statement), and several fields for the alternatives.

With this, I wanted the values of the input's of the alternatives to go straight to a list of alternatives instantiated in the respective bean.

So we have the class Option:

public class Opcao {

    private int idOpcao;
    private String nomeOpcao;

    public int getIdOpcao() {
        return idOpcao;
    }
    public void setIdOpcao(int idOpcao) {
        this.idOpcao = idOpcao;
    }
    public String getNomeOpcao() {
        return nomeOpcao;
    }
    public void setNomeOpcao(String nomeOpcao) {
        this.nomeOpcao = nomeOpcao;
    }

}

And the bean containing the list of options:

@ManagedBean
@ViewScoped
public class QuestaoBean {

    private List<Opcao> opcoes;

    public List<Opcao> getOpcoes() {
        return opcoes;
    }
    public void setOpcoes(List<Opcao> opcoes) {
        this.opcoes = opcoes;
    }
}
    
asked by anonymous 25.04.2015 / 06:43

2 answers

1

The adicionarOpcao() method adds a new option to the list with the data coming from <h:inputText> . After submitting the form data ( execute="@form" ) and method execution above <f:ajax> , which was triggered by <h:commandButton> , it updates the form ( render="@form" ) with the updated list data.

Controller

@ManagedBean
@ViewScoped
public class QuestaoBean {

    private List<Opcao> opcoes;
    private Opcao opcaoParaAdicionar;

    public QuestaoBean() {
         this.opcaoParaAdicionar = new Opcao();
    }

    public void adicionarOpcao() {
        if(opcoes == null) {
           opcoes = new ArrayList<>();
        }

        opcoes.add(opcao);
        opcao = new Opcao();
    }

    // getters e setters
}

View

<h:form>
    <ui:repeat value="#{questaoBean.opcoes}" var="opcao">
        <h:outputText value="#{opcao.nomeOpcao}" />
        </br>
    </ui:repeat>

    <h:inputText value="#{questaoBean.opcaoParaAdicionar.nomeOpcao}" />
    <h:commandButton value="Adicionar" action="#{questaoBean.adicionarOpcao}">
        <f:ajax render="@form" execute="@form" />
    </h:commandButton>
</h:form>
    
25.06.2015 / 22:00
0

Here is a simple example:

<h:selectOneMenu value="#{opcao.idOpcao}">
    <f:selectItems value="#{questaoBean.opcoes}" 
                   var="opcao" 
                   itemValue="#{opcao.id}"
                   itemLabel="#{opcao.nameOpcao}" />
</h:selectOneMenu>
<h:commandButton value="Submit" action="bean.acao" />

In this way the 'option' object will only instantiate the 'idOption', so in the 'bean.access' method code is needed to query the description of the option with its id.

The correct way would be to create an OpCodeConverter class that implements the Convert interface, allowing the full instantiation of 'option' and not just the 'idOption' attribute.     

06.05.2015 / 21:35