Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating input fields dynamically in JSF 2.0 and linking it to a backing bean

Tags:

jsf

jsf-2

My requirement is something like this. In a JSF(2.0) page, I have a section called Address. I have added a button which says "Add an Address". When the user clicks the button, new address fields(input text) should be generated dynamically (Line1, Line2, City etc..,). And when I click submit, all the values (Address 1, Address 2 ... Address N) should go to an array list.

So I need to

  1. Dynamically generate UI components on click on a button
  2. Link those UI components to a backing bean (Preferably to a list)
  3. Data tables should not be used for the above

It is very difficult to find proper JSF documentations online, so if anyone can help me out it would be great

Update : The answer posted by noone works good, but I want something more robust, like creating dynamic UI components from the Java Controller (The java bean, using HtmlPanelGrid component). I have been able to create components dynamically using htmlPanelGrid, but I cannot find a way to bind those generated components to the address list in the bean (The one which stores details of all the addresses)

like image 510
Bharath Bhandarkar Avatar asked Sep 05 '13 05:09

Bharath Bhandarkar


1 Answers

I assume that you have a class Address for the addresses. And a AddressBean with a List to keep the adresses.

The code might look like this (for the most basic scenario I can think of):

<h:form id="addressForm">
    <h:commandButton value="Add Address" action="#{addressBean.addAddress()}" immediate="true" execute="@this">
        <f:ajax render="addressForm" />
    </h:commandButton>
    <c:forEach items="#{addressBean.addressList}" var="address">
        <h:inputText value="#{address.street}" /><br />
    </c:forEach>
    <h:commandButton value="Save" action="#{addressBean.persistAddresses}" />
</h:form>

@ManagedBean
@ViewScoped
public class AddressBean {
    private List<Address> addressList = new ArrayList<Address>(); // getter+setter

    public void addAddress() {
        addressList.add(new Address());
    }

    public void persistAddresses() {
        // store the addressList filled with addresses
    }
}

public class Address {
    private String address; // getter+setter
}

<c:forEach> is taken from the JSTL. It might work with <ui:repeat>, but depending on your actual scenario it might not.

like image 131
noone Avatar answered Nov 01 '22 23:11

noone