This question already has an answer here:
How to send form input values and invoke a method in JSF bean
(1 answer)
Closed 7 years ago.
I have a inputText that i want to retrieve the value from but it looks like it`s not calling the setter method in my bean class. This is my bean class:
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "employees")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
public Employee() {}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
I am trying to get the firstName string in my ManagedBean class but it returns null. This is my controller class:
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import com.myapp.model.Employee;
#ManagedBean(name = "controller")
#SessionScoped
public class EmployeeController {
private Employee employee;
#PostConstruct
public void init()
{
employee = new Employee();
}
public Employee getEmployee()
{
return employee;
}
public void showInfo()
{
System.out.println("first name: " + employee.getFirstName());
}
}
This is my .xhtml file
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h2>Input:</h2>
<br/>
<p:panelGrid columns="2">
<p:outputLabel value = "First Name:" />
<p:inputText value = "#{controller.employee.firstName}" />
</p:panelGrid>
<br/>
<h:form>
<p:commandButton value="Save Edits" action="#{controller.showInfo()}"> </p:commandButton>
</h:form>
</h:body>
</html>
What am i doing wrong?
The <p:inputText> component must be part of the <h:form> component that is being submitted:
<h:form>
<h2>Input:</h2>
<br/>
<p:panelGrid columns="2">
<p:outputLabel value = "First Name:" />
<p:inputText value = "#{controller.employee.firstName}" />
</p:panelGrid>
<br/>
<p:commandButton value="Save Edits" action="#{controller.showInfo()}" />
</h:form>
Related
I am facing some problem to select multiple rows of h:dataTable. My code is below:
<h:dataTable value="#{reportBean.lstchalan}" var="chalan" >
<h:column >
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:selectBooleanCheckbox value="#{reportBean.checked[chalan.issueNo]}" />
</h:column>
...
</h:dataTable>
<h:commandButton value="submit" action="#{reportBean.submit()}" />
and Below is my backing bean:
public class ReportBean {
List<ChalanVo> checkedItems = new ArrayList<ChalanVo>();
private Map<String, Boolean> checked = new HashMap<String, Boolean>();
........
public List<ChalanVo> getCheckedItems() {
return checkedItems;
}
public void setCheckedItems(List<ChalanVo> checkedItems) {
this.checkedItems = checkedItems;
}
public Map<String, Boolean> getChecked() {
return checked;
}
public void setChecked(Map<String, Boolean> checked) {
this.checked = checked;
}
public String submit() {
checkedItems = new ArrayList<ChalanVo>();
for (ChalanVo dataItem : lstchalan) {
if (checked.get(dataItem.getIssueNo())) {
checkedItems.add(dataItem);
checked.remove(dataItem.getIssueNo());
}
}}
}
But I am getting an exception when execute the line for (ChalanVo dataItem : lstchalan) . lstchalan is giving null.Could you please help me to understand where I am doing wrong?
Here is a working, simplified example:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
#Named("test")
#ViewScoped
public class TestBean implements Serializable{
private static final long serialVersionUID = -1064219566884774973L;
private List<ChalanVo> lstChalans;
private Map<ChalanVo, Boolean> checkedItems = new HashMap<TestBean.ChalanVo, Boolean>();
public TestBean() {
lstChalans = new ArrayList<TestBean.ChalanVo>();
lstChalans.add(new ChalanVo("test1"));
lstChalans.add(new ChalanVo("test2"));
lstChalans.add(new ChalanVo("test3"));
}
public List<ChalanVo> getLstChalans() {
return lstChalans;
}
public void setLstChalans(List<ChalanVo> lstChalans) {
this.lstChalans = lstChalans;
}
public Map<ChalanVo, Boolean> getCheckedItems() {
return checkedItems;
}
public void setCheckedItems(Map<ChalanVo, Boolean> checkedItems) {
this.checkedItems = checkedItems;
}
public void save() {
System.out.println("save");
for (Entry<ChalanVo, Boolean> e : checkedItems.entrySet()) {
if (e.getValue()) {
System.out.println("checked: " + e.getKey().getIssueNo());
}
}
}
public class ChalanVo {
private String issueNo;
public ChalanVo(String issueNo) {
setIssueNo(issueNo);
}
public String getIssueNo() {
return issueNo;
}
public void setIssueNo(String issueNo) {
this.issueNo = issueNo;
}
}
}
With this xhtml:
<!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:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head />
<h:body>
<h:form>
<h:dataTable value="#{test.lstChalans}" var="chalan">
<h:column>
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:selectBooleanCheckbox value="#{test.checkedItems[chalan]}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Issue No" />
</f:facet>
<h:outputText value="#{chalan.issueNo}"/>
</h:column>
</h:dataTable>
<h:commandButton action="#{test.save()}" value="Submit" />
</h:form>
</h:body>
</html>
The save() method is able to list the selected items. I think your NullPointerException is unrelated to the checkbox thing. But anyway, you can do the selection like this.
This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 6 years ago.
I've got a datatable with values in which I get from my DB.
In my class myBean, I've got an Variable of type User to store the selected row. It just can be selected one row. Now I want to call this Variable from an other bean which is called printUser to get the selected User.
But it always prints null.
View
<p:dataTable id="userDT" var="user" value="#{myBean.getUserList()}" selection="#{myBean.selectedUser}"
rowKey="#{user.id}" >
<p:column selectionMode="single" style="width:16px;text-align:center"/>
<p:column width="200" headerText="ID">
<h:outputText value="#{user.id}" />
</p:column>
<p:column width="200" headerText="Firstname">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column width="250" headerText="Lastname">
<h:outputText value="#{user.lastname}" />
</p:column>
</p:dataTable>
myBean
#Named(value = "myBean")
#ManagedBean
#SessionScoped
public class myBean implements Serializable {
private static final long serialVersionUID = 1L;
private User selectedUser = new User();
public myBean() {
}
public List<User> getUserList() {
...
}
public Patient getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser= selectedUser;
}
}
User.java
public class User {
private Integer id;
private String firstname;
private String lastname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
printUser
#Named(value = "printUser")
#ManagedBean
#RequestScoped
public class printUser {
public printUser() {
}
public void getSelectedUserData(){
myBean bean = new myBean();
User user = new User();
user = bean.getSelectedUser();
System.err.println("UserID: " + user.getID());
}
}
Hope you undertand my Problem.
Thanks alot
Excuse my English
This is an example to use the entity of the selected row in the same page and in another page. The example use Lombok Getter,Setter and Data annotations for shortness:
The entity for the DataTable:
#Entity
#Data
#TableGenerator( name = "GEN_TestEntity1", table = "ID_Generator", pkColumnName = "GEN_KEY", pkColumnValue = "GEN_TestEntity1", valueColumnName = "GEN_VALUE" )
#NamedQuery( name = TestEntity1.QUERY_ALL_TESTENTITY1, query = "SELECT te1 FROM TestEntity1 te1" )
public class TestEntity1 implements Serializable
{
public static final String QUERY_ALL_TESTENTITY1 = "query_All_TestEntity1";
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.TABLE, generator = "GEN_TestEntity1" )
private int id;
#Column
private String name;
}
The ManagedBean as a controller:
#ManagedBean
#SessionScoped
public class EntityBean
{
#EJB
private EntitySER entitySER;
#Getter
#Setter
private TestEntity1 selectedEntity;
public List<TestEntity1> getAllTestEntity1()
{
return entitySER.getAllTestEntity1();
}
public void onRowSelect( SelectEvent event_ )
{
}
}
Another ManagedBean which uses the first one (if you really want it):
#ManagedBean
#RequestScoped
public class AnotherBean
{
#ManagedProperty( value="#{entityBean}" )
private EntityBean entityBean;
...
}
The stateless session bean:
#Stateless
#LocalBean
public class EntitySER
{
#PersistenceContext
private EntityManager em;
public List<TestEntity1> getAllTestEntity1()
{
Query q = em.createNamedQuery( TestEntity1.QUERY_ALL_TESTENTITY1 );
return q.getResultList();
}
}
The index page (index.xhtml):
<?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:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Page 1</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable id="table_TestEntity1" value="#{entityBean.allTestEntity1}" var="entity" selection="#{entityBean.selectedEntity}"
rowKey="#{entity.id}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{entityBean.onRowSelect}" update=":form:entID :form:entName"/>
<p:column>
#{entity.id}
</p:column>
<p:column>
#{entity.name}
</p:column>
</p:dataTable>
<p>
<h:outputLabel id="entID" value="#{entityBean.selectedEntity.id}"/>:
<h:outputLabel id="entName" value="#{entityBean.selectedEntity.name}"/>
</p>
<p>
<h:commandButton value="Page 2" action="/faces/another.xhtml"/>
</p>
</h:form>
</h:body>
</html>
The another Page (another.xhtml):
<?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:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Another Page</title>
</h:head>
<h:body>
<p>
The selected entity: #{entityBean.selectedEntity.id}:#{entityBean.selectedEntity.name}
</p>
<h:form>
<h:commandButton value="Back" action="/faces/index.xhtml"/>
</h:form>
</h:body>
</html>
This question already has answers here:
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 8 years ago.
I am new in JSF and facing problem in getting the drop down list. I don't want to use the #PostConstructor. I tried couple of sources on google but i don't know where i am making the mistake. please hep me out.
Managed Bean
package com.employee.registration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class EmployeeBean implements Serializable {
private static final long serialVersionUID = -5400118477202860998L;
private String firstName;
private String lastName;
private String emailID;
private int employeeNumber;
private String employeeDepartment;
private String dplist;
private List<DepartmentList> departmentList;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailID() {
return emailID;
}
public void setEmailID(String emailID) {
this.emailID = emailID;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeDepartment() {
return employeeDepartment;
}
public void setEmployeeDepartment(String employeeDepartment) {
this.employeeDepartment = employeeDepartment;
}
public List<DepartmentList> getDepartmentList() {
return departmentList;
}
public void setDepartmentList(List<DepartmentList> departmentList) {
this.departmentList = departmentList;
}
public List<DepartmentList> getDepartments() {
departmentList = new ArrayList<DepartmentList>();
departmentList.add(new DepartmentList("1", "Finance"));
departmentList.add(new DepartmentList("2", "Bnking"));
return departmentList;
}
public String getDplist() {
return dplist;
}
public void setDplist(String dplist) {
this.dplist = dplist;
}
}
Java Class
package com.employee.registration;
public class DepartmentList {
private String departmentId;
private String departmentName;
public DepartmentList(String departmentId, String departmentName) {
this.departmentId = departmentId;
this.departmentName = departmentName;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
XHTML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Employee Registration</title>
<h:outputStylesheet library="css" name="stylesheet.css" />
</h:head>
<h:body>
<h:form>
<fieldset>
<legend>Enter the Employees Information </legend>
<h:outputLabel id="firstName" value="First Name :" for="fName"></h:outputLabel>
<h:inputText id="fName" value="#{employeeBean.firstName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="lastName" value="Last Name :" for="lName"></h:outputLabel>
<h:inputText id="lName" value="#{employeeBean.lastName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="emailId" value="Email ID :"></h:outputLabel>
<h:inputText id="email" value="#{employeeBean.emailID}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="employeeNumberId" value="Employee Number :"></h:outputLabel>
<h:inputText id="empNumber" value="#{employeeBean.employeeNumber}"></h:inputText>
<br></br>
<h:outputLabel id="employeeDepartmentID" value="Employee Department"></h:outputLabel>
<h:inputText id="eDepartment"
value="#{employeeBean.employeeDepartment}"></h:inputText>
<br></br>
<h:selectOneMenu value="#{employeeBean.dplist}"></h:selectOneMenu>
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}"></f:selectItems>
<h:commandButton id="submit" value="Submit"
action="outputInformation"></h:commandButton>
</fieldset>
</h:form>
</h:body>
</html>
selectItems tag should be inside selectOneMenu :)
<h:selectOneMenu value="#{employeeBean.dplist}}">
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}" />
</h:selectOneMenu>
see tutorial here
At the First I will let u Know what i want to achieve and Later I will Show u the Problem.
In the Above screen Title and Description is from the AboutUs Entity and rest of the fields are for GeneralImage Entity.
Now what I want to achieve is when I click on create Button I want to persist data in two entities and have one to one relationship with each other
In order to do this I have written the below code which has the problem
AboutUs.java
package com.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.FetchType;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
#Entity
#NamedQuery(name = "AboutUs.findAboutUsByIdWithImages", query = "Select s from AboutUs s where
s.aboutusid = :aboutusid")
public class AboutUs implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private int aboutusid;
private String aboutustitle;
private String description;
public static final String FIND_ABOUTUS_BY_ID_WITH_IMAGES =
"AboutUs.findAboutUsByIdWithImages";
#OneToOne(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "imageid")
private GeneralImage image;
//Here Below I have Added Setters and Getters
……….
}
GeneralImage
#Entity
public class GeneralImage {
#Id
#GeneratedValue
private int imageid;
private String fileName;
private String categoryid;
private int orderofappearance;
private String mimetype;
private int filesize;
private int foreignkeyid;
#OneToOne(mappedBy="image", cascade=CascadeType.ALL)
private AboutUs aboutus;
//The Below Are The Setters and Getters
}
The below is My Facelets Image
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:body>
<p:dialog widgetVar="aboutusCreateDialogWidget"
id="aboutusCreateDialogId" height="400" width="1000" modal="true"
closable="true" draggable="false" resizable="false" showEffect="puff" hideEffect="fold"
header="Create About Us">
<h:form id="aboutusCreateDialogForm" prependId="false">
<h:panelGrid columns="2">
<h:outputText value="* #{msgs.aboutustitle}" />
<h:inputText value="#{aboutUsMB.aboutus.aboutustitle}" required="true" label="#
{msgs.aboutustitle}" >
<f:validateLength minimum="4" />
</h:inputText>
<h:outputText value="* #{msgs.aboutusescription}" />
<h:inputText value="#{aboutUsMB.aboutus.description}" required="true" label="#
{msgs.aboutusescription}" />
<h:outputText value="* #{msgs.categoryName}" />
<h:inputText value="#{generalImageMB.generalImage.categoryid}" required="true"
label="#{msgs.categoryName}" />
<h:outputText value="* #{msgs.orderOfAppearance}" />
<h:inputText value="#{generalImageMB.generalImage.orderofappearance}" required="true"
label="#{msgs.orderOfAppearance}" />
<h:outputText value="* #{msgs.mimetype}" />
<h:inputText value="#{generalImageMB.generalImage.mimetype}" required="true" label="#
{msgs.mimetype}" />
<h:outputText value="* #{msgs.fileSize}" />
<h:inputText value="#{generalImageMB.generalImage.filesize}" required="true" label="#
{msgs.fileSize}" />
</h:panelGrid>
<h:panelGrid columns = "2">
<p:commandButton value="#{msgs.create}" icon="ui-icon-plus"
action="#{aboutUsMB.createAboutus()}"
update=":messageGrowl :aboutusForm:aboutusTable"
oncomplete="closeDialogIfSucess(xhr, status, args, aboutusCreateDialogWidget,
'aboutusCreateDialogId')"
/>
<p:commandButton value="#{msgs.cancel}" icon="ui-icon-cancel" actionListener="#
{aboutusMB.resetAboutus()}" onclick="aboutusCreateDialogWidget.hide();" type="button" />
</h:panelGrid>
</h:form>
</p:dialog>
</h:body>
</html>
Next I have AboutUsMB
AboutUsMB
In AboutUsMB my createAboutus()
public void createAboutus()
{
try
{
aboutus.setImage(generalImage); //Here I am adding the generalImage object to about so that
//it can be persisted
aboutusFacade.save(aboutus);
closeDialog();
displayInfoMessageToUser("Created With Success......!");
loadAboutus();
resetAboutus();
}
catch (Exception e)
{
keepDialogOpen();
displayErrorMessageToUser("OOPS, We Could Not Create...... Try Again Later......!");
e.printStackTrace();
}
}
Later In Façade Classes
Save Method
AboutUsFacade
public interface AboutUsFacade {
//The Below I Am Adding Methods So That I Can Deal With Addition, Deletion and Updation of Users
public abstract void save(AboutUs aboutus);
}
Façade Implimentation Class
AboutUsFacadeImp
public class AboutUsFacadeImp implements AboutUsFacade
{
#EJB
private AboutUsDAO aboutusDAO;
#Override
public void save(AboutUs aboutus)
{
aboutusDAO.save(aboutus);
}
}
GenericDAO Class
public abstract class GenericDAO<T>
{
private final static String UNIT_NAME = "SmartRealtorsPU";
#PersistenceContext(unitName = UNIT_NAME)
private EntityManager em;
private Class<T> entityClass;
public GenericDAO(Class<T> entityClass)
{
this.entityClass = entityClass;
}
public void save(T entity) {
em.persist(entity);
}
}
So After Using the above Code I am not able to have generalImage data persisted only aboutus data has been persisted also u can see that the imageid which is the field of relationship is NULL
So cud any One rectify that What might be the Problem and also where i am wrong and what needs to be done
Is i am using one form to persist is causing the Problem
I had the same problem as you, you are mapping the bidirectional mapping on only one side.
In your AboutUsMB createAboutus() try to do the following:
Instead of
aboutus.setImage(generalImage);
do
aboutus.setImage(generalImage);
generalImage.setAboutus(aboutus);
I have using primefaces in my project. I need to create and delete field dynamically on my project. Here I am going to attached my code please find it
my xhtml page is
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:panelGrid border="0" columns="3" cellpadding="4" columnClasses="control-label">
<h:panelGrid columns="3" cellpadding="4" >
<h:outputText value="Individual Email"/>
<div>
<h:dataTable value="#{utilBean.attachments}" var="attachmentBean" binding="#{utilBean.data}" id="attachments">
<h:column>
<h:inputText id="attachment" value="#{attachmentBean.emailAddress}" binding="#{utilBean.attachment}"/>
</h:column>
<h:column>
<h:commandButton id="delete" value="Delete" immediate="true" actionListener="#{utilBean.deleteAddress}"/>
</h:column>
</h:dataTable>
<h:commandButton id="add" value="Add Email Address" immediate="true" actionListener="#{utilBean.addAddress}" />
</div>
<br/>
</h:panelGrid>
</h:panelGrid>
</ui:composition>
My Bean Is:
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIData;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
#ManagedBean
#SessionScoped
public class UtilBean{
private UIData data=null;
private UIInput attachment = null;
private List<AttachmentBean> attachments = new ArrayList<AttachmentBean>();
public void addAddress(ActionEvent event){
attachments.add(new AttachmentBean());
this.updateAddresses();
FacesContext.getCurrentInstance().renderResponse();
System.out.println("adress size:" + attachments.size());
}
public void deleteAddress(ActionEvent event){
int index = data.getRowIndex();
this.updateAddresses();
this.getAttachments().remove(index);
FacesContext.getCurrentInstance().renderResponse();
}
public void updateAddresses(){
System.out.println("adress sizedfdfdfdf:" + attachments.size());
#SuppressWarnings("unchecked")
List<AttachmentBean> list = (ArrayList<AttachmentBean>)data.getValue();
for(int i =0;i<data.getRowCount();i++){
data.setRowIndex(i);
list.get(i).setEmailAddress((String)getAttachment().getSubmittedValue());
}
data.setRowIndex(0);
}
public UIData getData() {
return data;
}
public void setData(UIData data) {
this.data = data;
}
public UIInput getAttachment() {
return attachment;
}
public void setAttachment(UIInput attachment) {
this.attachment = attachment;
}
public List<AttachmentBean> getAttachments() {
return attachments;
}
public void setAttachments(List<AttachmentBean> attachments) {
this.attachments = attachments;
}
}
And the Attachment Class is
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
#ManagedBean
#SessionScoped
public class AttachmentBean implements Serializable {
private static final long serialVersionUID = 1L;
private String emailAddress;
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public AttachmentBean() {
super();
}
}
I am not able to add textBox by clicking the add button. Please help. Thanks in advance.
You need to put the whole in a <h:form>. See also commandButton/commandLink/ajax action/listener method not invoked or input value not updated.
Another major mistake is here:
<h:dataTable ... binding="#{utilBean.data}">
...
<h:inputText ... binding="#{utilBean.attachment}"/>
Remove those binding attributes. UI components are request scoped and yet you're binding them to a session scoped bean. This would fail hard if you open the same page in multiple browser windows in the same session. See also How does the 'binding' attribute work in JSF? When and how should it be used?.
That said, the #ManagedBean #SessionScoped on AttachmentBean is completely unnecessary. Get rid of those annotations. The #SessionScoped on UtilBean is also rather strange. The #ViewScoped is much better at its place here. See also How to choose the right bean scope?