1

Possible Duplicate:
How to create dynamic JSF 1.2 form fields

I need to have a functionality where i can add a set of form elements like (textbox, dropdown menu) each time when i click on 'Add' button. When i click on 'delete' button next to component, it should be removed from the page. This functionality I needed in Java. Can anybody help on this?

Community
  • 1
  • 1
Tjs
  • 413
  • 4
  • 11
  • 23

1 Answers1

1

This is a working example. You should implement your own code according to your requirement.
Add a textBox to your page and then use an iterable component like ui:repeat, a4j:repeat or c:forEach to create multiple components.

<h:form id="test">  
  <ui:repeat value="#{myBean.myObjects}" var="obj">
    <h:inputText value="#{obj.text}" />
    <h:commandButton action="#{myBean.remove(obj)}" value="Remove"/><br/>
  </ui:repeat>
  <br/>
  <h:commandButton action="#{myBean.add()}" value="Add"/>  
</h:form>

In your managed bean getMyObjects() method should return the list to which you add items.

public class MyBean {
  private List<MyObject> objs = new ArrayList<MyObject>();

  public List<MyObject> getMyObjects() {
    return objs;
  }

  public void remove(MyObject t) {
    objs.remove(t);
  }

  public void add() {
    objs.add(new MyObject());
  }

  public class MyObject {
    private String text;

    public String getText() {
      return text;
    }

    public void setText(String text) {
      this.text = text;
    }

  }
}
prageeth
  • 7,159
  • 7
  • 44
  • 72
  • Thank you so much. tag is jsf tag? I wanted to use core tags to implement without using additional libraries like primefaces, richfaces etc. – Tjs Dec 14 '12 at 12:06
  • It is a `Facelets` tag. I think it would not be a matter for you. Read more at [here](http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/ui/repeat.html) and [here](http://www.jsftoolbox.com/documentation/facelets/10-TagReference/facelets-ui-repeat.html) – prageeth Dec 14 '12 at 12:21
  • @prageeth it could be a matter if OP is working on a mid-size project and tries to add Facelets in the middle. – Luiggi Mendoza Dec 14 '12 at 13:15
  • How will bind the values of dynamically generated components to backing bean? – Tjs Jan 08 '13 at 10:58
  • Use the `binding` attribute. See BalusC's answer to [this question](http://stackoverflow.com/questions/3510614/how-to-create-dynamic-jsf-1-2-form-fields) . If you still have problems please start a new thread then others could answer. – prageeth Jan 08 '13 at 13:13