简体   繁体   中英

Get component IDs and values that are generated dynamically

I have a questionnaire form in which components (questions) are generated all programatically in my backing bean.

In form submit event I need to collect all user inputs and store them in db.

But JSF does not recognize the dymanically generated components and only finds the ones that are in my Facelets page which are my panelgrid and submit button. This is my submit() method.

   public boolean submit() {
        UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
        UIComponent formComponent = viewRoot.findComponent("mainForm");  //form id
        HtmlForm form = (HtmlForm)formComponent;
        List<UIComponent> componentList = form.getChildren();
        for(int p=0; p<componentList.size(); p++) {
            UIComponent component = componentList.get(p);
                System.out.println("The Component ID is:"+component.getId());
        }
        return true;
}

So does anyone know where I can hunt my components other than the method above?

This is not the right way to collect submitted values.

You should instead bind the component's value attribute to a bean property. Eg

UIInput input = new HtmlInputText();
input.setId("input1");
input.setValueExpression("value", createValueExpression("#{bean.input1}", String.class));
form.getChildren().add(input);

This way JSF will just update the bean property the usual way.

private String input1; // +getter+setter

public void submit() {
    System.out.println(input1); // Look, JSF has already set it.
}

You could make use of a Map<String, Object> property to bring some more dynamics.

See also:

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