PrimeFaces: adding user using dialog not updating datatable through ajax - ajax

I have a page where some users are displayed through datatable.I have a option to add new user. when the add window is in the same page then the users are added to the datatable through ajax. But if I transfer the add option to primeface dialog the ajax functionality is not working and the datatable is not refreshed.
Here are my codes:
Code1: Here we have used the add user window in the same page -- this one works
<h:form>
<h:panelGrid id="grid" cellpadding="5" columns="2"
style="margin-bottom:10px">
<f:facet name="header">
<p:messages id="msgs" />
</f:facet>
<p:outputLabel for="firstname" value="Firstname:" />
<p:inputText id="firstname" value="#{userView.firstname}" />
<p:outputLabel for="surname" value="Surname:" />
<p:inputText id="surname" value="#{userView.lastname}"
required="true" requiredMessage="Surname is required." />
</h:panelGrid>
<h:panelGrid id="grid2">
<p:dataTable var="user" value="#{userView.getUsers()}">
<p:column headerText="FirstName">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column headerText="LastName">
<h:outputText value="#{user.lastname}" />
</p:column>
</p:dataTable>
</h:panelGrid>
<h:panelGrid columns="1">
<p:commandButton value="All" id="btnAll" process="#all" update="grid2"
actionListener="#{userView.save}" />
</h:panelGrid>
</h:form>
and my managed Bean is
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
#ManagedBean
public class UserView {
private String firstname;
private String lastname;
public List<User> dataUser;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public UserView()
{
dataUser = new ArrayList<User>();
dataUser.add(new User("AA", "LA"));
dataUser.add(new User("AB", "LB"));
dataUser.add(new User("AC", "LC"));
dataUser.add(new User("AD", "LD"));
dataUser.add(new User("AE", "LE"));
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public List<User> getUsers()
{
return dataUser;
}
public void save() {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Welcome " + firstname + " " + lastname));
dataUser.add(new User(firstname, lastname));
}
public class User{
public String firstname;
public String lastname;
public User(String fn, String ln)
{
this.firstname= fn;
this.lastname= ln;
}
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;
}
}
}
Code 2: if I use the add user in the pdialog then the page is not getting refreshed. The above managed bean remains same
<h:form>
<h:panelGrid id="grid2">
<p:dataTable var="user" value="#{userView.getUsers()}">
<p:column headerText="FirstName">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column headerText="LastName">
<h:outputText value="#{user.lastname}" />
</p:column>
</p:dataTable>
</h:panelGrid>
<h:panelGrid columns="1">
<p:commandButton value="AllPopup" id="btnAllPopup" process="#all"
update="grid2" onclick="PF('dlg1').show();" />
</h:panelGrid>
<p:dialog header="Basic Dialog" widgetVar="dlg1" minHeight="40">
<h:panelGrid id="gridpopup" cellpadding="5" columns="2"
style="margin-bottom:10px">
<p:outputLabel for="firstname1" value="Firstname:" />
<p:inputText id="firstname1" value="#{userView.firstname}" />
<p:outputLabel for="surname1" value="Surname:" />
<p:inputText id="surname1" value="#{userView.lastname}"
required="true" requiredMessage="Surname is required." />
</h:panelGrid>
<h:panelGrid columns="1">
<p:commandButton value="Alladd" id="btnAlladd" process="#all"
update="grid2" actionListener="#{userView.save}" />
</h:panelGrid>
</p:dialog>
</h:form>
Please help in understanding where the issue is

Related

Modal edit dialog on Primefaces with JSF

I'm trying to create some CRUD JSF application with edit/new screen implemented as a modal dialog. The problem is that I can't find a way how to make new and edit operation done by this dialog performed with ajax. With delete all was very simple (just ajax="true" option).
Here is a code of button which is used to show the dialog
<h:form id="dataForm">
<div class="ui-g">
<div class="ui-g-12 ui-md-9">
<p:dataGrid var="product" value="#{products.productList}" columns="3" layout="grid"
rows="12" paginator="true" id="products"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="6,12,16">
<f:event type="preRenderView" listener="#{products.preloadProductList}" />
<f:facet name="header">
Products
</f:facet>
<p:panel header="#{product.name}" style="text-align:center">
<h:panelGrid columns="1" style="width:100%">
<h:outputText value="#{product.name}"/>
<h:outputText value="#{product.price}"/>
<%-- Here new/edit dialog window is opened --%>
<p:commandLink update=":dataForm:productDetail" oncomplete="PF('productDialog').show()">
Edit
<f:setPropertyActionListener value="#{product}" target="#{products.product}"/>
</p:commandLink>
<p:commandLink update=":dataForm" action="#{products.deleteAction(product)}" ajax="true">
Delete
</p:commandLink>
</h:panelGrid>
</p:panel>
</p:dataGrid>
<ui:include src="WEB-INF/dialogs/edit_product.xhtml"/>
</div>
</div>
</h:form>
Here is dialog window which is moved to separete file edit_product.xhtml
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<p:dialog header="Product Info" widgetVar="productDialog" modal="true" showEffect="fade"
hideEffect="fade"
resizable="false">
<p:outputPanel id="productDetail" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty products.product}"
columnClasses="label,value">
<h:outputText value="Id:"/>
<h:outputText value="#{products.id}"/>
<h:outputText value="Name"/>
<h:inputText value="#{products.name}"/>
<h:outputText value="Price"/>
<h:inputText value="#{products.price}"/>
</p:panelGrid>
<h:commandButton value="Save" action="#{products.saveProduct}"/>
</p:outputPanel>
</p:dialog>
</ui:composition>
Here is Managed bean which is used by the Product dataGrid and dialog window.
#ManagedBean(name = "products")
#SessionScoped
public class ProductsBean {
private static final Logger logger = LoggerFactory.getLogger(ProductsBean.class);
#Inject
private ProductRepository productRepository;
private Product product;
private Collection<Product> productList;
public void preloadProductList(ComponentSystemEvent event) throws AbortProcessingException {
productList = productRepository.getAll();
}
public String getId() {
return String.valueOf(product.getId());
}
public void setId(String id) {
product.setId(Long.valueOf(id));
}
public String getName() {
return product.getName();
}
public void setName(String name) {
product.setName(name);
}
public int getPrice() {
return product.getPrice();
}
public void setPrice(int price) {
product.setPrice(price);
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
public Collection<Product> getProductList() {
logger.info("Get product list");
return productList;
}
public void newProductAction() {
this.product = new Product();
}
public void deleteAction(Product product) {
logger.info("Delete product");
productRepository.remove(product);
}
public void saveProduct() {
productRepository.merge(product);
}
}
No matter if I add ajax option or not the whole window is reloaded after Save button is pressed. Could you show me the right direction for the implementation, please?
P.S. If you need more code to answer you can find it here:
Main page with Product table https://github.com/usharik/GeekBrainsJavaEE/blob/master/lesson5-jpa/src/main/webapp/index.xhtml
Edit/New dialog https://github.com/usharik/GeekBrainsJavaEE/blob/master/lesson5-jpa/src/main/webapp/WEB-INF/dialogs/edit_product.xhtml

primefaces cascade selectonemenu

I have 3 dropdowns, the second has to be loaded based on the selected option of the first. And the third based on the selected option of the second.
This is the page:
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Empresa:" for="selectCompany" />
<p:selectOneMenu id="selectCompany" value="#{dropdownBean.company}"
converter="entityConverter" effect="fade" effectSpeed="200"
var="company">
<p:ajax process="#this" event="change"
update="selectBranch, selectVendor" />
<f:selectItems value="#{dropdownBean.companies}" var="companyItem"
itemLabel="#{companyItem.corporateName}" itemValue="#{companyItem}" />
<p:column>
<h:outputText value="#{company.corporateName}" />
</p:column>
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Surcursal:" for="#selectBranch" />
<p:selectOneMenu id="#selectBranch" value="#{dropdownBean.branch}"
converter="entityConverter" effect="fade" effectSpeed="200"
var="branch">
<p:ajax process="#this" event="change" update="#selectVendor" />
<f:selectItem itemLabel="SELECCIONE SUCURSAL" itemValue=""
noSelectionOption="true" />
<f:selectItems value="#{dropdownBean.branches}" var="branchItem"
itemLabel="#{branchItem.branchName}" itemValue="#{branchItem}" />
<p:column>
<h:outputText value="#{branch.branchName}" />
</p:column>
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Vendedor: " for="#selectVendor" />
<p:selectOneMenu id="#selectVendor" value="#{dropdownBean.vendor}"
converter="entityConverter" effect="fade" effectSpeed="200"
var="vendor">
<f:selectItem itemLabel="SELECCIONE VENDEDOR" itemValue=""
noSelectionOption="true" />
<f:selectItems value="#{dropdownBean.vendors}" var="vendorItem"
itemLabel="#{vendorItem.vendorName}" itemValue="#{vendorItem}" />
<p:column>
<h:outputText value="#{vendor.vendorName}" />
</p:column>
</p:selectOneMenu>
</h:panelGrid>
And the backbean:
#ManagedBean
public class DropdownBean {
#Inject
private CompanyBC companyBC;
#Inject
private BranchBC branchBC;
#Inject
private VendorBC vendorBC;
private V_Companies company;
private V_Branches branch;
private V_Vendors vendor;
private List<V_Companies> companies;
private List<V_Branches> branches;
private List<V_Vendors> vendors;
#PostConstruct
public void allCompanies() {
companies = companyBC.allCompanies();
}
public List<V_Companies> getCompanies() {
return companies;
}
public void setCompanies(List<V_Companies> companies) {
this.companies = companies;
}
public List<V_Branches> getBranches() {
if(company!=null)
branches = branchBC.allCompanyBranches(company.getCompanyId());
return branches;
}
public void setBranches(List<V_Branches> branches) {
this.branches = branches;
}
public List<V_Vendors> getVendors() {
if(company!=null && branch!=null)
vendors = vendorBC.allBranchVendors(company.getCompanyId(), branch.getBranchId());
return vendors;
}
public void setVendors(List<V_Vendors> vendors) {
this.vendors = vendors;
}
public V_Companies getCompany() {
return company;
}
public void setCompany(V_Companies company) {
this.company = company;
}
public V_Branches getBranch() {
return branch;
}
public void setBranch(V_Branches branch) {
this.branch = branch;
}
public V_Vendors getVendor() {
return vendor;
}
public void setVendor(V_Vendors vendor) {
this.vendor = vendor;
}
}
The first two dropdowns work great but the last one does not. Apparently cannot be more than one p:ajax for the same event or something like that. Any suggestions please?
adding a listener worked:
<p:ajax process="#this" listener="#{userEditMB.onBranchChange}" event="change" update="selectVendor" />
public void onBranchChange(AjaxBehaviorEvent event) {
setBranch((V_Branches) ((UIOutput) event.getSource()).getValue());
vendors = vendorBC.allBranchVendors(getBranch().getCompanyId(),
getBranch().getBranchId());
}
I tried listener before but passing the Id's as parameters. Passing AjaxBehaviorEvent and casting to the object was the answer for me. I hope helps someone
Thanks!

JSF form is not submitted

Please check this form the form data is submitted but setAttendancedata method is working..
but classname, sectionname, date is not set in variable ..
xhtml:
<p:panel header="Attendance Entry" style="margin-top:10px">
<p:growl id="msgs" showDetail="true" />
<h:form id="attendance">
<h:panelGrid id="detail" columns="10" styleClass="grid"
cellspacing="10" cellpadding="40">
<h:outputText value="Date: " />
<h:outputText value="" id="popupDate">
<f:convertDateTime pattern="yyyy-mm-dd" />
</h:outputText>
<p:calendar value="#{StudentAttendanceComponent.date}"
id="popupCal" />
<h:outputText value="Class :" />
<p:selectOneMenu id="classname"
value="#{StudentAttendanceComponent.classname}">
<f:selectItem itemLabel="Select Class Name" itemValue="" />
<f:selectItems value="#{PreferencesClassComponent.classnames}" />
</p:selectOneMenu>
<h:outputText value="Section :" />
<p:selectOneMenu id="sectionname"
value="#{StudentAttendanceComponent.sectionname}">
<f:selectItem itemLabel="Select Section Name" itemValue="" />
<f:selectItems value="#{PreferencesSectionComponent.sectionnames}" />
</p:selectOneMenu>
<p:commandButton ajax="false" immediate="true" value="Go"
action="#{StudentAttendanceComponent.setAttendanceData}"
update="msgs" icon="ui-icon-check"></p:commandButton>
</h:panelGrid>
</h:form>
Model:
#Scope("session")
#Component("StudentAttendanceComponent")
public class StudentAttendanceComponentImpl implements
StudentAttendanceComponent {
/**
* Data type variable that provides CRUD operations for StudentAttendance
* entities
*
*/
#Autowired
StudentMasterService studentMasterService;
private Date date = new Date();
private String[] attData;
private StudentAttendance studentattendance;
private String classname;
private String sectionname;
private List<StudentAttendance> studentAttendances;
#Autowired
private StudentAttendanceDAO studentAttendanceDAO;
/**
* Service injected by Spring that provides CRUD operations for
* StudentAttendance entities
*
*/
#Autowired
private StudentAttendanceService studentAttendanceService;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getSectionname() {
return sectionname;
}
public void setSectionname(String sectionname) {
this.sectionname = sectionname;
}
public void setAttendanceData() {
// TODO Auto-generated method stub
System.out.println(classname+sectionname);
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Filter Data", "Class " + classname + ", section " + sectionname+", date " + getDate().getDate());
FacesContext.getCurrentInstance().addMessage("msgs", msg);
}
The problem you have is, that you set the immediate="true" attribute within your p:commandButton. Because of this attribute, several JSF Lifecycles are skipped.
Check these links:
http://docs.oracle.com/javaee/1.4/tutorial/doc/JSFIntro10.html
http://balusc.blogspot.co.at/2006/09/debug-jsf-lifecycle.html#AddImmediateTrueToUICommandOnly
http://balusc.blogspot.co.at/2006/09/debug-jsf-lifecycle.html#WhenShouldIUseTheImmediateAttribute

capture selected text from inputTextArea primefaces jsf

I want to capture selected text from inputTextArea on ajax dblclick or select event.How can I do this ?
The code below selects everything in the text area (which I don't want). Thank you very much.
<h:form id="form">
<p:panel header="Select Text">
<h:panelGrid columns="3" cellpadding="5">
<h:outputText value="Text: " />
<p:inputTextarea id="textarea"
value="#{selectedTextBean.selectedText}">
<p:ajax event="select" update="selectedText" />
</p:inputTextarea>
<h:outputText id="selectedText"
value="#{selectedTextBean.selectedText}" />
</h:panelGrid>
</p:panel>
</h:form>
Here is SelectedTextBean
#ManagedBean
#ViewScoped
public class SelectedTextBean {
public SelectedTextBean() {
}
private String selectedText;
public String getSelectedText() {
return selectedText;
}
public void setSelectedText(String selectedText) {
this.selectedText = selectedText;
}
}
You can use this plugin jquery-textrange.
xhtml
<p:inputTextarea onselect="setSelectedText()" />
<p:remoteCommand name="setSelectedTextCommand"
actionListener="#{mainBean.setSelectedText()}"
update="currentSelectedText" />
Selected Text is:
<h:outputText value="#{mainBean.selectedTextInArea}"
id="currentSelectedText" />
<h:outputScript library="js" name="jquery-textrange.js" />
<script>
function setSelectedText() {
var range = $('.ui-inputtextarea').textrange();// general selector
setSelectedTextCommand([{name: 'selectedText', value: range.text}]);
}
</script>
Bean
private String selectedTextInArea;
public void setSelectedText() {
FacesContext context = FacesContext.getCurrentInstance();
Map map = context.getExternalContext().getRequestParameterMap();
selectedTextInArea = (String) map.get("selectedText");
}
public String getSelectedTextInArea() {
return selectedTextInArea;
}
public void setSelectedTextInArea(String selectedTextInArea) {
this.selectedTextInArea = selectedTextInArea;
}
And Here's a live demo on Primefaces TextArea Selection, and on github.
You can do that sending a parameter to a remote command as follows:
The View
<h:form id="form">
<p:panel header="Select Text">
<h:panelGrid columns="3" cellpadding="5">
<h:outputText value="Text: " />
<h:panelGroup>
<p:inputTextarea id="textarea"
value="#{selectedTextBean.selectedText}" onselect="processSelection();" />
<p:remoteCommand name="sendSelection" actionListener="#{selectedTextBean.onSelect}" update="selectedText" process="#this" />
</h:panelGroup>
<h:outputText id="selectedText"
value="#{selectedTextBean.selectedText}" />
</h:panelGrid>
</p:panel>
</h:form>
<script>
function processSelection() {
var selectedText = (!!document.getSelection) ? document.getSelection() :
(!!window.getSelection) ? window.getSelection() :
document.selection.createRange().text;
sendSelection([{name: 'selectedText', value: selectedText}]);
}
</script>
Note that the text selection changes depending on the browser.
The Bean
import java.io.Serializable;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#ViewScoped
public class SelectedTextBean implements Serializable {
public SelectedTextBean() {
}
private String selectedText;
public void onSelect() {
FacesContext context = FacesContext.getCurrentInstance();
Map map = context.getExternalContext().getRequestParameterMap();
selectedText = (String) map.get("selectedText");
}
public String getSelectedText() {
return selectedText;
}
public void setSelectedText(String selectedText) {
this.selectedText = selectedText;
}
}

PrimeFaces PropertyNotFoundException Target Unreachable, 'null' returned null

I am having problems with the site I am creating. I am new to Faces 2.0 and was only using JSP and now shifting to Faces 2.0. I have a page that adds and deletes a location Zip Code. The edit part works but the add part, I am having an error:
PropertyNotFoundException, Target Unreachable, 'null' returned null.
on following value:
value="#{zipCodeMaintennanceBean.selectedZipCode.description}"
I dont know why it does not work because the edit part works and they use the same ManagedBean.
I am using Spring 3.1.3 With Hibernate and PrimeFaces 3.5. I hope someone answers my question as I dont know how to solve this.
I suspect that whenever I click the button, a new object is being created as I am using a #RequestScoped annotation.
I tried to from instantiating the entity class on #PostConstruct Method, even instantiating the entity on the declaration and setting an empty string on description and nothing works.
It doesnt get to call save() method and seems to get stuck on the Update Model Values Phase
Below is my xhtml page:
<!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"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:composition template="/WEB-INF/views/template.xhtml">
<ui:define name="content">
<table border="0" width="100%">
<tr align="center">
<td><c:if test="${not empty param.login_error}">
<div class="error"
style="font-family: serif; font-size: medium; color: red;">
#{msg['label.login.invalidlogon']}<br />
#{sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}
</div>
</c:if> <c:if test="">
<div class="message"
style="font-family: serif; font-size: medium; color: red;">
${sessionScope.messageVariable}</div>
</c:if> </td>
</tr>
</table>
<p:panelGrid columns="3">
<h:form id="form">
<f:facet name="header">
<p:row>
<p:column colspan="3">#{msg['usrmnt.header']}</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<h:outputLabel for="userSearch" value="Search ZipCode/Description" />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="userSearch"
value="#{zipCodeMaintennanceBean.searchString}">
</p:inputText>
</p:column>
<p:column>
<p:commandButton value="#{msg['usrmnt.searchbutton']}"
actionListener="#{zipCodeMaintennanceBean.search}"
update="panel,dataTable" process="#form" />
<p:commandButton value="Add"
actionListener="#{zipCodeMaintennanceBean.triggerAdd}"
update="panel,:#{p:component('displayadd')}"
oncomplete="addDialog.show()" />
</p:column>
</p:row>
<p:row>
<p:column colspan="3" styleClass="ui-widget-header">
<p:spacer height="0" />
</p:column>
</p:row>
<p:row>
<p:column colspan="3">
<p:outputPanel id="panel">
<p:dataTable id="dataTable" var="zip"
value="#{zipCodeMaintennanceBean.zipCodes}" paginator="true"
rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15"
rendered="#{zipCodeMaintennanceBean.hasSearchResult}"
selectionMode="single"
selection="#{zipCodeMaintennanceBean.selectedZipCode}"
rowKey="#{zip.zipcode}">
<p:ajax event="rowSelect"
listener="#{zipCodeMaintennanceBean.onRowSelect}"
oncomplete="editDialog.show()"
update=":#{p:component('display')}" />
<p:ajax event="rowUnselect"
listener="#{zipCodeMaintennanceBean.onRowUnselect}" />
<f:facet name="header">
Users
</f:facet>
<p:column>
<f:facet name="header">
<h:outputText value="Zip Code" />
</f:facet>
<h:outputText value="#{zip.zipcode}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{zip.description}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</p:column>
</p:row>
<p:dialog header="Add ZipCode" widgetVar="addDialog" id="addDialog"
modal="true" showEffect="clip" hideEffect="fold" dynamic="true">
<p:outputPanel autoUpdate="true">
<p:panelGrid cellpadding="4" id="displayadd"
rendered="#{zipCodeMaintennanceBean.addMode}"
styleClass="maintennancePanelGrid">
<f:facet name="header">
<p:row>
<p:column colspan="3">
<h:outputText value="Add Zip Code" />
</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<h:outputLabel for="zipcodeAdd" value="Zip Code:" />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="zipcodeAdd"
value="#{zipCodeMaintennanceBean.selectedZipCode.zipcode}"
label="Zip Code" required="true">
<f:validateLength for="userName" minimum="4" maximum="6"></f:validateLength>
</p:inputText>
</p:column>
<p:column>
<p:message for="zipcodeAdd"></p:message>
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputLabel for="descriptionAdd" value="Description: " />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="descriptionAdd"
required="true"
value="#{zipCodeMaintennanceBean.selectedZipCode.description}"
label="Description"></p:inputText>
</p:column>
<p:column>
<p:message for="descriptionAdd"></p:message>
</p:column>
</p:row>
<f:facet name="footer">
<p:row>
<p:column styleClass="text-align:center" colspan="3">
<p:commandButton value="Submit"
update=":#{p:component('displayadd')}"
action="#{zipCodeMaintennanceBean.add}"
oncomplete="if (!args.validationFailed) addDialog.hide()" process="#form" />
</p:column>
</p:row>
<p:row>
<p:column colspan="3">
</p:column>
</p:row>
</f:facet>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
<p:dialog header="Edit ZipCode" resizable="false" id="editDialog"
widgetVar="editDialog" modal="true" showEffect="clip"
hideEffect="fold" closeOnEscape="true" dynamic="true">
<p:outputPanel autoUpdate="true">
<p:panelGrid cellpadding="4" id="display"
rendered="#{zipCodeMaintennanceBean.hasSelectedZipCode}"
styleClass="maintennancePanelGrid">
<f:facet name="header">
<p:row>
<p:column colspan="3">
<h:outputText value="Edit Zip Code" />
</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<h:outputLabel for="zipcode" value="Zip Code:" />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="zipcode"
value="#{zipCodeMaintennanceBean.selectedZipCode.zipcode}"
label="Zip Code" disabled="true">
<f:validateLength for="userName" minimum="4" maximum="6"></f:validateLength>
</p:inputText>
</p:column>
<p:column>
<p:message for="zipcode"></p:message>
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputLabel for="descripton" value="Description: " />
</p:column>
<p:column>
<p:inputText styleClass="new-fld" id="description"
required="true"
value="#{zipCodeMaintennanceBean.selectedZipCode.description}"
label="Description"></p:inputText>
</p:column>
<p:column>
<p:message for="description"></p:message>
</p:column>
</p:row>
<f:facet name="footer">
<p:row>
<p:column styleClass="text-align:center" colspan="3">
<p:commandButton value="Submit"
update="panel,:#{p:component('display')}"
action="#{zipCodeMaintennanceBean.save}"
oncomplete="if (!args.validationFailed) editDialog.hide()" />
<p:commandButton value="Delete"
update="panel,:#{p:component('display')}"
action="#{zipCodeMaintennanceBean.delete}"
oncomplete="if (!args.validationFailed) editDialog.hide()"
process="#this">
</p:commandButton>
<p:confirmDialog global="true" showEffect="fade"
hideEffect="explode">
<p:commandButton value="Yes" type="button"
styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />
<p:commandButton value="No" type="button"
styleClass="ui-confirmdialog-no" icon="ui-icon-close" />
</p:confirmDialog>
</p:column>
</p:row>
<p:row>
<p:column colspan="3">
</p:column>
</p:row>
</f:facet>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</p:panelGrid>
</ui:define>
</ui:composition>
</html>
Below is my Backing Bean:
package com.siteam.web.bean;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.siteam.web.invsys.dao.ZipCodeDao;
import com.siteam.web.invsys.entities.TblZipcodes;
#ManagedBean(name = "zipCodeMaintennanceBean")
#RequestScoped
#Service
public class ZipCodeMaintennanceBean {
private TblZipcodes selectedZipCode = new TblZipcodes();
private boolean hasSelectedZipCode = false;
private List<TblZipcodes> zipCodes = new ArrayList<TblZipcodes>();
private ZipCodeDao zipCodeDao;
private boolean hasSearchResult = false;
private String searchString;
private boolean addMode;
public void triggerAdd() {
init();
this.addMode = true;
}
public String add() {
try {
this.selectedZipCode.setDateupdated(Calendar.getInstance()
.getTime());
this.zipCodeDao.add(this.selectedZipCode);
this.zipCodeDao.refresh(this.selectedZipCode);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Zip Code Saved. ",
"Saved Zip Code"));
context.getExternalContext().getFlash().setKeepMessages(true);
init();
this.addMode = false;
return "zipmnt";
} catch (DataIntegrityViolationException ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_WARN, "Error:",
"ZipCode Already Exists"));
ex.printStackTrace();
return "";
} catch (NullPointerException npe) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", npe.getMessage()));
npe.printStackTrace();
return "";
} catch (Throwable th) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", th.getCause()
.getMessage()));
th.printStackTrace();
return "";
}
}
public String save() {
try {
this.selectedZipCode.setDateupdated(Calendar.getInstance()
.getTime());
this.zipCodeDao.update(this.selectedZipCode);
this.zipCodeDao.refresh(this.selectedZipCode);
FacesContext context = FacesContext.getCurrentInstance();
init();
// RequestContext.getCurrentInstance().execute("editDialog.hide()");
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Zip Code Saved. ",
"Saved Zip Code"));
context.getExternalContext().getFlash().setKeepMessages(true);
hasSearchResult = false;
this.hasSelectedZipCode = false;
return "zipmnt";
} catch (DataIntegrityViolationException ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_WARN, "Error:",
"ZipCode Already Exists"));
ex.printStackTrace();
return "";
} catch (NullPointerException npe) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", npe.getMessage()));
npe.printStackTrace();
return "";
} catch (Throwable th) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", th.getCause()
.getMessage()));
th.printStackTrace();
return "";
}
}
public String delete() {
try {
this.zipCodeDao.delete(this.selectedZipCode);
FacesContext context = FacesContext.getCurrentInstance();
init();
// RequestContext.getCurrentInstance().execute("editDialog.hide()");
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Zip Code Deleted. ",
"Deleted Zip Code"));
context.getExternalContext().getFlash().setKeepMessages(true);
hasSearchResult = false;
this.hasSelectedZipCode = false;
return "zipmnt";
} catch (DataIntegrityViolationException ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_WARN, "Error:",
"ZipCode Already Exists"));
ex.printStackTrace();
return "";
} catch (NullPointerException npe) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", npe.getMessage()));
npe.printStackTrace();
return "";
} catch (Throwable th) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Error:", th.getCause()
.getMessage()));
th.printStackTrace();
return "";
}
}
#PostConstruct
public void init() {
this.hasSelectedZipCode = false;
this.hasSearchResult = false;
this.addMode = false;
this.selectedZipCode = new TblZipcodes();
this.selectedZipCode.setDescription("");
this.zipCodes.clear();
}
public void search() {
hasSearchResult = false;
TblZipcodes zipCode = new TblZipcodes();
zipCode.setZipcode(searchString);
this.zipCodes = zipCodeDao.findZipCodes(zipCode);
if (zipCodes.size() > 0) {
hasSearchResult = true;
}
}
public TblZipcodes getSelectedZipCode() {
return selectedZipCode;
}
public void setSelectedZipCode(TblZipcodes selectedZipCode) {
this.selectedZipCode = selectedZipCode;
}
public boolean isHasSelectedZipCode() {
return hasSelectedZipCode;
}
public void setHasSelectedZipCode(boolean hasSelectedZipCode) {
this.hasSelectedZipCode = hasSelectedZipCode;
}
public List<TblZipcodes> getZipCodes() {
return zipCodes;
}
public void setZipCodes(List<TblZipcodes> zipCodes) {
this.zipCodes = zipCodes;
}
public ZipCodeDao getZipCodeDao() {
return zipCodeDao;
}
#Autowired
public void setZipCodeDao(ZipCodeDao zipCodeDao) {
this.zipCodeDao = zipCodeDao;
}
public boolean isHasSearchResult() {
return hasSearchResult;
}
public void setHasSearchResult(boolean hasSearchResult) {
this.hasSearchResult = hasSearchResult;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public void onRowSelect(SelectEvent event) {
this.selectedZipCode = (TblZipcodes) event.getObject();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Selected Zip Code", "Zip Code Selected: "
+ selectedZipCode.getZipcode());
zipCodeDao.refresh(this.selectedZipCode);
FacesContext.getCurrentInstance().addMessage(null, msg);
this.hasSelectedZipCode = true;
}
public void onRowUnselect(UnselectEvent event) {
// FacesMessage msg = new FacesMessage("Car Unselected", ((Car)
// event.getObject()).getModel());
this.selectedZipCode = new TblZipcodes();
this.hasSelectedZipCode = false;
}
public boolean isAddMode() {
return addMode;
}
public void setAddMode(boolean addMode) {
this.addMode = addMode;
}
}
Below is my Zip Code Entity Code
package com.siteam.web.invsys.entities;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "TBL_ZIPCODES", schema = "INVSYS")
public class TblZipcodes implements java.io.Serializable {
private String zipcode;
private String description = "";
private Date dateupdated;
private Set<TblCustomer> tblCustomers = new HashSet<TblCustomer>(0);
public TblZipcodes() {
}
public TblZipcodes(String zipcode) {
this.zipcode = zipcode;
}
public TblZipcodes(String zipcode, String description, Date dateupdated,
Set tblCustomers) {
this.zipcode = zipcode;
this.description = description;
this.dateupdated = dateupdated;
this.tblCustomers = tblCustomers;
}
#Id
#Column(name = "ZIPCODE", unique = true, nullable = false, length = 5)
public String getZipcode() {
return this.zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
#Column(name = "DESCRIPTION", length = 50)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Temporal(TemporalType.DATE)
#Column(name = "DATEUPDATED", length = 7)
public Date getDateupdated() {
return this.dateupdated;
}
public void setDateupdated(Date dateupdated) {
this.dateupdated = dateupdated;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "tblZipcodes")
public Set<TblCustomer> getTblCustomers() {
return this.tblCustomers;
}
public void setTblCustomers(Set<TblCustomer> tblCustomers) {
this.tblCustomers = tblCustomers;
}
#Override
public boolean equals(Object newObject) {
return newObject instanceof TblZipcodes;
}
// This must return the same hashcode for every Foo object with the same key.
public int hashCode() {
return this.getClass().hashCode();
}
}
Thank you in advance.
In your dataTable you are using the same variable for row selection.
selectionMode="single" selection="#{zipCodeMaintennanceBean.selectedZipCode}"
When no row is selected the selectedZipCode attribute will be null and you will continue to get an Exception.
You could simply use another instance of TblZipcodes for the addDialog.
PS: Some time ago someone reported a bug when giving the same name to id and widgetVar as you did in addDialog, check if this is a problem in version 3.5.

Resources