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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With