Dynamically add/remove jsf components example

Program:

 

dynamic.xhtml:

[html]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<h:head>

</h:head>

<h:body>
<h:form>
<h:dataTable value="#{dynBean.dynList}" var="myListElement">
<h:column>
<h:panelGrid>
<h:outputText value="www.ngdeveloper.com"></h:outputText>
</h:panelGrid>
</h:column>
</h:dataTable>
<h:commandButton value="Add" action="#{dynBean.addToMyList}" />
<h:commandButton value="Remove" action="#{dynBean.removeFromMyList}" />
</h:form>
</h:body>

</html>
[/html]

DynamicBean.java:

[java]
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dynBean")
@ViewScoped
@SessionScoped
public class DynamicBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Object> dynList;

public DynamicBean() {
dynList = new ArrayList<Object>();
}

public void removeFromMyList() {
dynList.remove(0);

}

public void addToMyList() {
dynList.add(new Object());
}

public List<Object> getdynList() {
return (dynList);
}

}

[/java]

Output:

dynamic add

dynamically remove

2 comments

Leave a Reply