Dynamically create input fields in JSF 2.0 and bind it to bean support

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

Therefore i need

  • Dynamically create user interface components at the click of a button
  • Associate these user interface components with a bean base (preferably in a list)
  • Data tables should not be used for the above

It is very difficult to find the right JSF documentation on the Internet, so if anyone can help me, it will be great

Update: the answer that no one publishes works well, but I want something more robust, like creating dynamic user interface components from a Java controller (java bean using the HtmlPanelGrid component). I was able to dynamically create components using htmlPanelGrid, but I cannot find a way to bind these generated components to the address list in the bean (the one that stores data about all addresses)

+6
source share
1 answer

I assume you have an Address class for addresses. And AddressBean with List to save addresses.

The code might look like this (for the most basic scenario that 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 JSTL. It may work with <ui:repeat> , but depending on your actual scenario, this may not be.

+5
source

Source: https://habr.com/ru/post/953208/


All Articles