0

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
disasterkid
  • 6,948
  • 25
  • 94
  • 179
  • 3
    Unrelated to the concrete problem, why don't you just bind the values of dynamic component values to bean property/properties? – BalusC Sep 18 '12 at 13:22
  • Don't understand your "Unrelated to the concrete problem" comment, but I have used binding on my component generation. I'll give it a closer look and if it didn't work I'll come back to this. – disasterkid Sep 18 '12 at 13:32
  • 1
    Because it doesn't answer your **current question** (but it might be a much better way to solve your concrete functional requirement for which you thought that the approach as in your current question is the right solution). Please note that I'm not talking about `binding` attribute, but just about `value` attribute. Those should refer bean properties (which can be just a `Map` by the way). You may find some hints in one of those answers: http://stackoverflow.com/search?q=user%3A157882+%5Bdynamic-forms%5D – BalusC Sep 18 '12 at 13:34
  • Awesome. My binding is working. Thank you @BalusC. I'm new to StackOverflow so if you post an answer I can somehow select it as the working answer. You know better. Cheers. – disasterkid Sep 18 '12 at 13:41

1 Answers1

0

This is not the right way to collect submitted values.

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

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555