Search code examples
jsfprimefacesjavabeansselectonemenu

Add a new p:SelectOneMenu to a JSF page dynamically from the Backing bean


i want to add dynamically an new p:SelectOneMenu to my panelGrid here

<h:panelGrid id="panel_grid" columns="1" style="margin-bottom:10px"cellpadding="5" >

   <p:outputLabel for="firstQuestionDropDown" value={InsererAffaireController.firstQuestion.libeleQuestion}"
   <p:selectOneMenu id="firstQuestionDropDown" value="#{InsererAffaireController.firstQuestion.libeleQuestion}" style="width:150px">
      <p:ajax listener="#{InsererAffaireController.displayNextQuestion()}" update="panel_grid" />
      <f:selectItems value="#{InsererAffaireController.firstQuestion.listLibeleReponses}" />
    </p:selectOneMenu>

            <!-- Here i want to add my new SelectOneMenu -->    
</h:panelGrid>

I managed to do that from the managed bean but the problem is that i can't populate the new SelectOneMenu and i don't know how to add a f:selectItems to it here is the method that add the new p:SelectOneMenu to the panel grid but it still empty

    public void displayNextQuestion() {
       nextQuestion = getNextQuestion();
       OutputLabel nextQuestionLabelUI = new OutputLabel();
       nextQuestionLabelUI.setValue(nextQuestion.getLibeleQuestion());

       SelectOneMenu nextQuestionDropDown = new SelectOneMenu() ;

       List<SelectItem> selectItems = new ArrayList<>();

       for (String s : nextQuestion.getListLibeleReponses()) {

        selectItems.add(new SelectItem(s, s));
        System.out.println(selectItems.get(0).getLabel());
       }
       // How can i add the selectitems to the SelectOneMenu
       UIComponent panelGrid = findComponent("panel_grid");
       panelGrid.getChildren().add(nextQuestionLabelUI);
       panelGrid.getChildren().add(nextQuestionDropDown) ;
       RequestContext.getCurrentInstance().update("panel_grid");

}

Solution

  • You can use the UISelectItems class like this:

    ...
    UISelectItems selectItemsComponent = new UISelectItems();
    selectItemsComponent.setValue(selectItems);
    nextQuestionDropDown.getChildren().add(selectItemsComponent);
    ...