p:selectOneMenu value does not get set after ajax call - java

Im trying to have the option set to a specific value from the backend after an AJAX-call, however although all other field-types are successfully set the selectOneMenu is not. Im using Primefaces/JSF.
xhtml:
<p:inputText id="cpr" value="#{customerbean.customer.cpr}">
<p:ajax event="change" listener="#{customerbean.fetchCustomerDatafromCBS}" update="#form" immediate="true" >
<f:param name="cprNumber" value="#{customerbean.customer.cpr}"/>
</p:ajax>
<f:validator validatorId="cprValidator" />
</p:inputText>
<p:selectOneMenu id="gender" value="#{customerbean.customer.gender}" required="#{!customerbean.disabled}" requiredMessage="#{text['validation.error.required.gender']}" disabled="#{customerbean.disabled}">
<f:selectItem itemLabel="Select One" itemValue="" noSelectionOption="true" />
<f:selectItem itemLabel="Male" itemValue="Male" />
<f:selectItem itemLabel="Female" itemValue="Female" />
</p:selectOneMenu>
bean:
getCustomer().setGender(fetchedCustomer.getGender().trim());
NOTE
I just discovered that the value IS set (because the database row is inserted with the correct value) - but the selectOneMenu UI object on the browser does not reflect that.
ENTIRE VIEW:
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:t="http://myfaces.apache.org/tomahawk">
<ui:composition template="commonLayout.xhtml">
<ui:define name="content">
<p:panelGrid columns="2" styleClass="companyHeaderGrid" >
<f:facet name="header">
Create customer
</f:facet>
<h:outputLabel for="cpr" value="CPR" />
<h:outputLabel for="passportno" value="Passport No." />
<p:inputText id="cpr" value="#{customerbean.customer.cpr}">
<p:ajax event="change" listener="#{customerbean.fetchCustomerDatafromCBS}" update="#form" immediate="true" >
<f:param name="cprNumber" value="#{customerbean.customer.cpr}"/>
</p:ajax>
<f:validator validatorId="cprValidator" />
</p:inputText>
<p:inputText id="passportno" value="#{customerbean.customer.passportno}" readonly="#{customerbean.disabled}">
<f:validator validatorId="passportnoValidator" />
</p:inputText>
<h:outputLabel for="name" value="Name"/>
<h:outputLabel for="nationality" value="Nationality" />
<p:inputText id="name" value="#{customerbean.customer.name}" required="true" requiredMessage="#{text['validation.error.required.name']}" readonly="#{customerbean.disabled}"/>
<p:inputText id="nationality" value="#{customerbean.customer.nationality}" required="true" requiredMessage="#{text['validation.error.required.nationality']}" readonly="#{customerbean.disabled}" />
<h:outputLabel for="dob" value="Date of Birth" />
<h:outputLabel for="address" value="Address" />
<p:calendar id="dob" value="#{customerbean.customer.dob}" pattern="ddmmyyyy" readonly="#{customerbean.disabled}" />
<p:inputText id="address" value="#{customerbean.customer.address}" readonly="#{customerbean.disabled}" />
<h:outputLabel for="mailingaddress" value="Mailing Address" />
<h:outputLabel for="gender" value="Gender" />
<p:inputText id="mailingaddress" value="#{customerbean.customer.mailingAddress}" readonly="#{customerbean.disabled}" />
<p:selectOneMenu id="gender" value="#{customerbean.customer.gender}" required="#{!customerbean.disabled}" requiredMessage="#{text['validation.error.required.gender']}" disabled="#{customerbean.disabled}">
<f:selectItem itemLabel="Select One" itemValue="" noSelectionOption="true" />
<f:selectItem itemLabel="Male" itemValue="Male" />
<f:selectItem itemLabel="Female" itemValue="Female" />
</p:selectOneMenu>
<h:outputLabel for="mobileno" value="Mobile No." />
<h:outputLabel for="faxno" value="Fax No." />
<p:inputText id="mobileno" value="#{customerbean.customer.mobileno}" required="true" requiredMessage="#{text['validation.error.required.mobileno']}" validatorMessage="#{text['validation.error.mobileno']}" readonly="#{customerbean.disabled}" >
<f:validateLongRange minimum="0" maximum="99999999999999" />
</p:inputText>
<p:inputText id="faxno" value="#{customerbean.customer.faxno}" readonly="#{customerbean.disabled}" />
<h:outputLabel for="otherno" value="Other No." />
<h:outputLabel for="primaryemail" value="Primary email" />
<p:inputText id="otherno" value="#{customerbean.customer.otherno}" readonly="#{customerbean.disabled}" />
<p:inputText id="primaryemail" value="#{customerbean.customer.primaryemail}" required="false" validatorMessage="#{text['validation.error.required.email']}" readonly="#{customerbean.disabled}">
<f:validateRegex pattern="([\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z])?" />
</p:inputText>
<h:outputLabel for="alternativeemail" value="Alternative email" />
<p:inputText id="alternativeemail" value="#{customerbean.customer.alternativeemail}" required="false" validatorMessage="#{text['validation.error.required.email']}" readonly="#{customerbean.disabled}">
<f:validateRegex pattern="([\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z])?" />
</p:inputText>
<h:outputLabel for="maritalstatus" value="Marital status" />
<h:outputLabel for="nochildren" value="No. of Children" />
<p:selectOneMenu id="maritalstatus" value="#{customerbean.customer.maritalStatus}" disabled="#{customerbean.disabled}">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItem itemLabel="Single" itemValue="Single" />
<f:selectItem itemLabel="Married" itemValue="Married"/>
<f:selectItem itemLabel="Divorced" itemValue="Divorced"/>
<f:selectItem itemLabel="Widow" itemValue="Widow"/>
</p:selectOneMenu>
<p:inputText id="nochildren" value="#{customerbean.customer.nochildren}" readonly="#{customerbean.disabled}" />
<f:facet name="footer">
<center>
<p:commandButton action="#{customerbean.add(customerbean.customer)}" ajax="false" value="Save" icon="ui-icon-check" />
<p:commandButton value="Reset" update="cpr passportno name nationality dob address mailingaddress gender genderhidden mobileno faxno otherno primaryemail alternativeemail maritalstatus maritalstatushidden nochildren messages" process="#this"
icon="ui-icon-cancel">
<pe:resetInput for="cpr passportno name nationality dob address mailingaddress gender genderhidden mobileno faxno otherno primaryemail alternativeemail maritalstatus maritalstatushidden nochildren"/>
</p:commandButton>
</center>
</f:facet>
</p:panelGrid>
<p:inputText id="genderhidden" type="hidden" value="#{customerbean.customer.gender}" />
<p:inputText id="maritalstatushidden" type="hidden" value="#{customerbean.customer.maritalStatus}" />
</ui:define>
</ui:composition>
</html>

Set customerbean to #ViewScoped
eg:
#ManagedBean
#ViewScoped
public class customerbean implements Serializable {
}

Ok, I found the culprit: noSelectionOption="true" on the f:selectItem. Once I remove that, it works fine. The reason maritalStatus worked is because it doesnt have the noSelectionOption attribute.

Related

Value didn't set selectOneMenu to ManagedBean

I have a selectOneMenu that loads anothers in demand. See:
<h:outputLabel value="Tabela: *" />
<p:selectOneMenu id="selectOneMenuTabela"
converter="entityConverter"
value="#{orcamentoMB.tabelaSelecionada}" effect="fade"
required="true" requiredMessage="A Tabela é obrigatória">
<f:selectItem itemLabel="Selecione uma Tabela" itemValue="" />
<f:selectItems value="#{orcamentoMB.tabelas}" var="tabela"
itemLabel="#{tabela.nome}" itemValue="#{tabela}" />
<p:ajax event="change" update="selectOneMenuProcedimento" />
</p:selectOneMenu>
<h:outputText value="Procedimento: *" />
<p:selectOneMenu id="selectOneMenuProcedimento"
disabled="#{orcamentoMB.tabelaSelecionada == null}"
converter="entityConverter" filter="true"
filterMatchMode="contains"
value="#{orcamentoMB.itemTabelaProcedimentoSelecionado}"
effect="fade" required="true"
requiredMessage="O procedimento é obrigatório">
<f:selectItem itemLabel="Selecione um Procedimento" itemValue="" />
<f:selectItems value="#{orcamentoMB.tabelaSelecionada.itens}"
var="item" itemLabel="#{item.procedimento.nome}"
itemValue="#{item}" />
<p:ajax event="change"
update="localAplicacao, selectOneMenuDente,selectOneMenuFace" />
</p:selectOneMenu>
<h:outputText value="Local Aplicação: *" />
<h:outputText id="localAplicacao"
value="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.localAplicacao.descricao}" />
<h:outputText value="Dente: *" />
<p:selectOneMenu id="selectOneMenuDente" converter="entityConverter"
filter="true" filterMatchMode="contains"
disabled="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento == null || orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.dentesAsList.size() == 0}"
value="#{orcamentoMB.denteSelecionado}" effect="fade">
<f:selectItem itemLabel="Selecione um Dente" itemValue="" />
<f:selectItems
value="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.dentesAsList}"
var="dente" itemLabel="#{dente.descricao}" itemValue="#{dente}" />
</p:selectOneMenu>
<h:outputText value="Face: *" />
<p:selectOneMenu id="selectOneMenuFace" converter="entityConverter"
disabled="#{orcamentoMB.itemTabelaProcedimentoSelecionado.procedimento.facesAplicacaoAsList.size() == 0 || orcamentoMB.itemTabelaProcedimentoSelecionado == null}"
value="#{orcamentoMB.faceSelecionada}" effect="fade">
<f:selectItem itemLabel="Selecione uma Face" itemValue="" />
<f:selectItems
value="#{orcamentoMB.itemOrcamento.itemTabelaProcedimento.procedimento.facesAplicacaoAsList}"
var="face" itemLabel="#{face.descricao}" itemValue="#{face}" />
</p:selectOneMenu>
The "selectOneMenuTabela" and "selectOneMenuProcedimento" works fine, the value are setted in ManagedBean, but the others not.
When i try to execute this commandButton bellow:
<p:commandButton value="Incluir" icon="ui-icon-plus" process="#this"
disabled="#{orcamentoMB.bean.situacao.codigo != 'AGUARDANDO_ACEITACAO'}"
update=":formManterOrcamento:tabViewManterOrcamento:tabProcedimentos,:formManterOrcamento:panelTotais"
actionListener="#{orcamentoMB.addItemOrcamento}" />
THe value inside "denteSelecionado" is null, and the values inside "selectOneMenuFace" aren't loaded.
Since you are having p:ajax event="change"on first two selectOneMenu they are being submitted that is why you are getting those value. To process them on click of commandButton add those component ids to process attribute along with #this like process like process="#this,selectOneMenuFace,selectOneMenuDente,.."
If the component is disabled or readOnly then they won't be processed.
Hope this helps

Java Primefaces how to work with elements placed in dataTable column header

When "selectOneMenu" is placed in the "dataTable" column header it:
1) triggers row sorting everytime it is opened or after the button next to it is clicked and "selectOneMenu" is opened (it shouldn't be like that);
2) fails to assign value to the backing bean.
How can "selectOneMenu" be attached to the column header so that these problems wouldn't occur?
*.xhtml code with dataTable which causes 1) and 2) problems:
<h:form id="someForm0">
<p:dataTable id="sdt" var="variable" value="#{otherBean.tableModel}" rows="10">
<p:column sortBy="#{variable.name}" filterBy="#{variable.name}" filterMatchMode="contains" >
<f:facet name="header">
<h:outputText value="Name"/>
<h:panelGrid columns="2" cellpadding="1">
<p:selectOneMenu id="abc" value="#{userBean.someChars}">
<f:selectItem itemLabel="" itemValue="select" />
<f:selectItem itemLabel="AAA" itemValue="AAA" />
<f:selectItem itemLabel="BBB" itemValue="BBB" />
<f:selectItem itemLabel="CCC" itemValue="CCC" />
</p:selectOneMenu>
<h:commandButton id="btn" value="Submit" type="submit" action="#{userBean.submitChars}"/>
</h:panelGrid>
</f:facet>
<h:outputText value="#{variable.name}"/>
</p:column>
</p:dataTable>
</h:form>
Backing bean code:
#ManagedBean
public class UserBean
{
private String someChars;
public String getSomeChars()
{
return someChars;
}
public void setSomeChars(String someChars)
{
this.someChars = someChars;
}
public String submitChars()
{
if(getSomeChars() != null)
{
System.out.println("Selected chars are: " + getSomeChars());
}
else
{
System.out.println("Selected chars are equal to null!");
}
return null;
}
}
Here is fragment of the previously mentioned *.xhtml code, and selectOneMenu works just great when placed into the basic form:
<h:form id="someForm">
<p:selectOneMenu id="abc" value="#{userBean.someChars}">
<f:selectItem itemLabel="" itemValue="select" />
<f:selectItem itemLabel="AAA" itemValue="AAA" />
<f:selectItem itemLabel="BBB" itemValue="BBB" />
<f:selectItem itemLabel="CCC" itemValue="CCC" />
</p:selectOneMenu>
<h:commandButton id="btn" value="Submit" type="submit" action="#{userBean.submitChars}"/>
</h:form>
I think the last resort would be adding elements from the dataTable column header to the dataTable header:
<h:form id="someForm1">
<p:dataTable id="sdt" var="variable" value="#{otherBean.tableModel}" rows="10">
<f:facet name="header">
<h:panelGrid columns="2" cellpadding="1">
<p:selectOneMenu id="abc" value="#{userBean.someChars}">
<f:selectItem itemLabel="" itemValue="select" />
<f:selectItem itemLabel="AAA" itemValue="AAA" />
<f:selectItem itemLabel="BBB" itemValue="BBB" />
<f:selectItem itemLabel="CCC" itemValue="CCC" />
</p:selectOneMenu>
<h:commandButton id="btn" value="Submit" type="submit" action="#{userBean.submitChars}"/>
</h:panelGrid>
</f:facet>
<p:column sortBy="#{variable.name}" filterBy="#{variable.name}" filterMatchMode="contains" >
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{variable.name}"/>
</p:column>
</p:dataTable>
</h:form>
Try as below :
<h:form id="someForm0">
<p:dataTable id="sdt" ...>
<p:column headerText="header">
<p:selectOneMenu id="abc" value="#{userBean.someChars}">
<f:selectItem itemLabel="" itemValue="select" />
<f:selectItem itemLabel="AAA" itemValue="AAA" />
<f:selectItem itemLabel="BBB" itemValue="BBB" />
<f:selectItem itemLabel="CCC" itemValue="CCC" />
<p:ajax event="valueChange" update=":someForm0:sdt"/>
</p:selectOneMenu>
</p:column>
</p:dataTable>
<h:commandButton ....>
</h:form>
UserBean.java
private String someChars;
public String getSomeChars() {
return someChars;
}
public void setSomeChars(Stirng someChars) {
this.someChars = someChars;
}

dynamic page content with primefaces

I'm creating a web page. The content should change according to user selection.
I require 2 radio buttons which give the option to select one day and many days (start date and end date) if one day selected page should display one calender to select date else two calenders to select start date and end date I tried to use rendered propety with ajax but I can't view calenders how could i do this
my xhtml
<h:form id="f1">
<p:growl id="createmsg"/>
<h:panelGrid columns="2" cellpadding="10">
<p:panel id="add_visitor_details_pnl" style="width:100%">
<h:panelGrid id="grid" columns="2" cellpadding="10">
<h:outputText value="Organization :" />
<p:selectOneMenu editable="true" value="#{visitorBean.organization}" style="width:160px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{visitorBean.organizations}" />
</p:selectOneMenu>
<h:outputText value="Visitor Name :" />
<p:selectOneMenu value="#{visitorBean.name}" style="width:160px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{visitorBean.names}" />
</p:selectOneMenu>
<h:outputText value="Visitor ID :" />
<p:selectOneMenu value="#{visitorBean.id}" style="width:160px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{visitorBean.ids}" />
</p:selectOneMenu>
<h:outputText value="Purpose :" />
<p:inputTextarea id="purpose_it" value="#{visitorBean.purpose}" required="true" autoResize="false"
requiredMessage="Enter Purpose" rows="10" cols="50"/>
</h:panelGrid>
<h:panelGrid columns="1" cellpadding="10">
<p:selectOneRadio id="customRadio" value="#{visitorBean.option}" >
<f:selectItem itemLabel="Create a one day appointment" itemValue="1" />
<f:selectItem itemLabel="create a day period appointment" itemValue="2" />
<p:ajax event="change" listener="#{visitorBean.selectDayType()}"
update=":f1:add_visitor_details_pnl" />
</p:selectOneRadio>
</h:panelGrid>
<h:panelGrid id="date" columns="3" cellpadding="10">
<h:outputText id="date1" value="Date" rendered="#{visitorBean.cal1}"/>
<p:calendar id="calender_Cal1" value="#{visitorBean.date_time}"
pattern="yyyy-MM-dd" rendered="#{visitorBean.cal1}"
required="true" requiredMessage="Enter Date Time"/>
<p:calendar id="calender_Cal2" value="#{visitorBean.date_time}"
pattern="yyyy-MM-dd" rendered="#{visitorBean.cal2}"
required="true" requiredMessage="Enter Date Time"/>
</h:panelGrid>
<h:panelGrid columns="2" cellpadding="10">
<p:commandButton id="submit_visitor_Btn" value="Create"
action="#{visitorBean.submitVisitorData()}"
update=":f1:visitor_dataTable,:f1:grid,:f1:createmsg"/>
</h:panelGrid>
my ajax mthod
public void selectDayType(){
if(option =="1")
cal1 = "true";
else if(option =="2"){
cal1="true";
cal2="true";
}
Try surrounding the calendars with a:
<p:outputPanel id="someId" >
...
</p:outputPanel>
Primefaces - Output Panel

Primefaces 3.5 SNAPSHOT datatable push (websocket) update

I'm using Mojarra, PF 3.5 SNAPSHOT, Tomcat 7.0.32 and trying to make a datatable update itself when changes have been done by other clients. I'm also using CDF beans along with MyCODI, #ViewAccessScoped.
When I was using 3.4, in-row editing (instead of in-cell editing) and standard #ConversationScoped it was working.
This is the xhtml:
<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:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:t="http://myfaces.apache.org/tomahawk">
<ui:composition template="commonLayout.xhtml">
<ui:define name="content">
<p:growl id="growlmessage" showDetail="false" autoUpdate="true"/>
<p:contextMenu for="staffTable">
<p:menuitem value="Open" update="staffTable" icon="ui-icon-close" actionListener="#{staffbean.onOpen}" />
<p:menuitem value="Delete" update="staffTable" icon="ui-icon-close" onclick="confirmation.show()" />
</p:contextMenu>
<p:confirmDialog id="confirmDialog" message="#{text['viewedit.delete.confirm']}"
header="#{text['viewedit.delete.header']}" severity="alert" widgetVar="confirmation" appendToBody="true" closable="false" visible="false" >
<p:commandButton action="#{staffbean.onDelete}" ajax="true" value="Yes" oncomplete="confirmation.hide()" icon="ui-icon-check" />
<p:commandButton value="No" onclick="confirmation.hide()" type="button" icon="ui-icon-closethick" />
</p:confirmDialog>
<p:dataTable id="staffTable" var="staff" widgetVar="staffList" value="#{staffbean.objectList}" paginator="true" rows="15" paginatorPosition="bottom" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" currentPageReportTemplate="#{text['table.staff.filter.count']}" rowsPerPageTemplate="15,25,50,100" emptyMessage="#{text['table.staff.filter.notfound']}" filteredValue="#{staffbean.filteredObject}" editable="true" editMode="cell" draggableColumns="true" rowKey="#{staff.id}" selection="#{staffbean.selectedObject}" selectionMode="single">
<f:facet name="header">
<p:columnGroup type="header">
<p:row>
<p:column colspan="4">
<h:outputText value="#{text['table.staff.header']}" />
</p:column>
</p:row>
<p:separator/>
<p:row>
<p:panelGrid columns="5" styleClass="headerGrid">
<p:column colspan="2">
<h:outputText value="#{text['table.filter.global']}" />
<p:inputText id="globalFilter" onkeyup="staffList.filter()" style="width:150px" />
</p:column>
<p:column colspan="2">
<p:selectOneMenu id="pageonly" value="#{staffbean.pageOnly}" >
<f:selectItem itemLabel="#{text['dataexporter.pageonly']}" itemValue="true" />
<f:selectItem itemLabel="#{text['dataexporter.entirepage']}" itemValue="false" />
<p:ajax event="change" listener="#{staffbean.exportXLS}" update="#form" immediate="true" />
</p:selectOneMenu>
<h:commandLink>
<p:graphicImage id="exportPage" value="/resources/img/excel.png" />
<p:dataExporter type="xls" target="staffTable" fileName="staff" pageOnly="#{staffbean.pageOnly}"/>
<p:tooltip for="exportPage" value="#{text['dataexporter.tooltip']}" showEffect="fade" hideEffect="fade" />
</h:commandLink>
</p:column>
</p:panelGrid>
</p:row>
</p:columnGroup>
</f:facet>
<p:column id="nameColumn" headerText="#{text['label.name']}" sortBy="#{staff.name}" filterBy="#{staff.name}" filterMatchMode="contains">
<p:cellEditor>
<f:facet id="nameoutput" name="output">
<h:outputText value="#{staff.name}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{staff.name}" style="width:100%" required="true" requiredMessage="#{text['validation.error.required.name']}"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column id="staffnoColumn" headerText="#{text['label.staffno']}" sortBy="#{staff.staffno}" filterBy="#{staff.staffno}" filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{staff.staffno}" />
</f:facet>
<f:facet id="staffliststaffno" name="input">
<p:inputText value="#{staff.staffno}" style="width:100%" required="true" requiredMessage="#{text['validation.error.required.staffno']}">
<pe:keyFilter regEx="/^\d+$/" preventPaste="false"/>
<f:validator validatorId="staffnoValidator" />
<f:validator validatorId="numericValidator" />
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
<f:facet name="footer" id="footer">
There are #{fn:length(staffbean.objectList)} staff in total.
</f:facet>
<p:ajax event="cellEdit" listener="#{staffbean.onEdit}" update="#form" />
</p:dataTable>
</ui:define>
<ui:define name="socket">
<p:socket channel="/ba" >
<p:ajax event="message" update="ba_staffTable" />
</p:socket>
</ui:define>
</ui:composition>
Bean:
public void update(Object object) {
if (!getEm().getTransaction().isActive()) {
getEm().getTransaction().begin();
}
try {
get().merge(object);
get().getTransaction().commit();
} catch (PersistenceException e) {
if (ExceptionUtil.is(e, ConstraintViolationException.class) || ExceptionUtil.is(e, RollbackException.class)) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ResourceLoader.MESSAGES.getProperty("staff.error.dbconstraint"), null));
if (getEm().getTransaction().isActive()) {
getEm().getTransaction().rollback();
}
}
}
PushContextFactory.getDefault().getPushContext().push("/ba", "");
}
Your table id is staffTable not ba_staffTable

CDI params in #PostConstruct

I think my question is similar to this but haven't found it to work
<f:metadata>
<f:viewParam id="id" name="id" value="#{detailsBean.id}"/>
</f:metadata>
Why can't I do this with #Named and utilize CDI:
#Named
#RequestScoped
public class DetailsBean {
private Contacts detailsContact;
#EJB
ContactsFacade contactsEJB;
private int id;
public DetailsBean() {
System.out.println("details bean called");
}
#PostConstruct
public void onLoad() {
detailsContact = contactsEJB.find(id);
}
I'm not able to log the id.
Of course, #ManagedProperty is incompatible with CDI.
*****UPDATE*****
some xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
template="../template.xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:f="http://java.sun.com/jsf/core">
<ui:define name="head">
<f:metadata>
<f:viewParam name="paginator" value="#{contactsBean.contactsTablePaginator}"/>
<f:viewParam name="rows" value="#{contactsBean.contactsTableRows}"/>
</f:metadata>
</ui:define>
<ui:define name="content">
<p:growl id="growl" showDetail="true"/>
<p:panel id="contactsPanel" >
<h:form id ="contactsForm">
<p:dataTable id="contactsTable" value="#{contactsBean.contacts}" selection="#{detailsBean.detailsContact}" var="contacts" widgetVar="contactsTable"
selectionMode="single" rowSelectListener="#{contactsBean.rowSelect}" rowUnselectListener="#{contactsBean.rowUnSelect}"
onRowUnselectUpdate="detailsForm" onRowSelectUpdate="detailsForm"
paginator="#{contactsBean.contactsTablePaginator}" rows="#{contactsBean.contactsTableRows}" rowsPerPageTemplate="5,10,15,25,50,100"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search:" />
<p:inputText id="globalFilter" onkeyup="contactsTable.filter()" style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column filterStyle="display:none" filterBy="#{contacts.name}" headerText="Name" style="width:200px">
<h:outputText value="#{contacts.name}" />
</p:column>
<p:column filterStyle="display:none" filterBy="#{contacts.street}" headerText="Street" style="width:280px">
<h:outputText value="#{contacts.street}" />
</p:column>
<p:column filterStyle="display:none" filterBy="#{contacts.city}" headerText="City" style="width:150px">
<h:outputText value="#{contacts.city}" />
</p:column>
<p:column filterStyle="display:none" filterBy="#{contacts.state}" headerText="State" style="width:50px">
<h:outputText value="#{contacts.state}" />
</p:column>
<p:column filterStyle="display:none" filterBy="#{contacts.zip}" headerText="Zip" style="width:100px">
<h:outputText value="#{contacts.zip}" />
</p:column>
<p:column filterStyle="display:none" filterBy="#{contacts.country}" headerText="Country" style="width:150px">
<h:outputText value="#{contacts.country}" />
</p:column>
<p:column filterStyle="display:none" filterBy="#{contacts.sent}" headerText="Sent" style="width:50px">
<h:outputText value="#{contacts.sent}" />
</p:column>
</p:dataTable>
<p:ajaxStatus >
<f:facet name="start">
<h:graphicImage value="../resources/images/ajax-loader-bar.gif" />
</f:facet>
<f:facet name="complete">
<h:graphicImage value="../resources/images/ajax-loader-bar-still.gif" />
</f:facet>
<f:facet name="default">
<h:graphicImage value="../resources/images/ajax-loader-bar-still.gif" />
</f:facet>
</p:ajaxStatus>
<br />
<p:commandLink value="View All" action="#{contactsBean.viewAll}" />
<p:commandLink value="Default View" action="#{contactsBean.viewDefault}" />
<p:commandLink value="Advanced Search" action="search?faces-redirect=true" />
<br />
</h:form>
<br />
</p:panel>
<br />
<br />
<h:form id="detailsForm">
<p:panel id="detailsPanel" visible="#{detailsBean.visible}" >
<h:panelGrid id="detailsPanelGrid" cellpadding="2" cellspacing="2" columns="3" >
<h:outputText value="Name :" />
<p:inputText id="name" value="#{detailsBean.detailsContact.name}" style="width:400px" />
<p:message for="name" />
<h:outputText value="Email :" />
<p:inputText id="email" value="#{detailsBean.detailsContact.email}" style="width:400px" validatorMessage="Must be a valid email address. EX: test#test.com" >
<f:validateRegex pattern="[a-zA-Z0-9]+#[a-zA-Z0-9]+\.[a-zA-Z0-9]+"/>
<p:ajax event="blur" update="emailMsg" />
</p:inputText>
<p:message id="emailMsg" for="email" />
<h:outputText value="Street :" />
<p:inputText id="street" value="#{detailsBean.detailsContact.street}" style="width:400px" />
<p:message for="street" />
<h:outputText value="City :" />
<p:inputText id="city" value="#{detailsBean.detailsContact.city}" style="width:400px" />
<p:message for="city" />
<h:outputText value="State :" />
<p:inputText id="state" value="#{detailsBean.detailsContact.state}" style="width:400px" validatorMessage="Length is greater than 2" >
<f:validateLength maximum="2" />
<p:ajax event="blur" update="stateMsg" />
</p:inputText>
<p:message id="stateMsg" for="state" />
<h:outputText value="Country :" />
<p:inputText id="country" value="#{detailsBean.detailsContact.country}" style="width:400px" />
<p:message for="country" />
<h:outputText value="Phone :" />
<p:inputText id="phone" value="#{detailsBean.detailsContact.phone}" style="width:400px"/>
<p:message for="phone" />
<h:outputText value="Guests :" />
<p:inputText id="guests" value="#{detailsBean.detailsContact.guests}" style="width:400px"/>
<p:message for="guests" />
<h:outputText value="Arrival :" />
<p:calendar id="arrival" value="#{detailsBean.detailsContact.arrival}" showOn="button" />
<p:message for="arrival" />
<h:outputText value="Departure :" />
<p:calendar id="departure" value="#{detailsBean.detailsContact.departure}" showOn="button" />
<p:message for="departure" />
<h:outputText value="Message :" />
<p:inputTextarea id="message" effectDuration="30" style="width:400px;height:100px;" value="#{detailsBean.detailsContact.message}" />
<p:message for="message" />
<h:outputText value="Departure :" />
<p:calendar id="inserted" value="#{detailsBean.detailsContact.inserted}" showOn="button"/>
<p:message for="inserted" />
<h:outputText value="Sent :" />
<h:selectBooleanCheckbox id="sent" value="#{detailsBean.detailsContact.sent}" />
<p:message for="sent" />
<br />
</h:panelGrid>
<p:commandButton value="Submit" action="#{detailsBean.updateContactDetails}" update="contactsForm, growl, stateMsg" />
<p:commandButton value="Close" action="#{detailsBean.handleClose}" update="contactsForm, detailsForm" />
</p:panel>
</h:form>
</ui:define>
</ui:composition>
more java code:
package com.atlanticpkg.view.beans;
import com.atlanticpkg.model.entities.Contacts;
import com.atlanticpkg.util.FacesUtils;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
#Named(value = "detailsBean")
#RequestScoped
public class EditBean {
private Contacts detailsContact;
private boolean visible = false;
#Inject
ContactsBean contactsBean;
public EditBean() {
}
#PostConstruct
public void onLoad() {
}
public void handleClose() {
this.setVisible(false);
this.setDetailsContact(new Contacts());
}
public void updateContactDetails() {
try {
contactsBean.getContactsEJB().edit(detailsContact);
FacesUtils.addMessage(detailsContact.getName() + " was updated successfully!");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", e.toString()));
}
}
}
and even more:
#Named(value = "contactsBean")
#RequestScoped
public class ContactsBean {
#Inject
EditBean editBean;
#EJB
private ContactsFacade contactsEJB;
private List<Contacts> contacts = new ArrayList<Contacts>();
private boolean contactsTablePaginator = true;
private int contactsTableRows = 10;
private Contacts selectedContact = new Contacts();
public ContactsBean() {
}
#PostConstruct
public void onLoad() {
updateContactsList();
}
public String viewDefault() {
contactsTablePaginator = true;
contactsTableRows = 10;
return "index?faces-redirect=true&includeViewParams=true";
}
public String viewAll() {
contactsTablePaginator = false;
contactsTableRows = 100;
return "index?faces-redirect=true&includeViewParams=true";
}
public void updateContactsList() {
contacts.clear();
contacts = contactsEJB.findAll();
}
public void rowSelect(SelectEvent event) {
editBean.setVisible(true);
editBean.setDetailsContact((Contacts) event.getObject());
}
public void rowUnSelect(UnselectEvent event) {
editBean.setVisible(false);
editBean.setDetailsContact(new Contacts());
}
}
The inputText boxes populate fine. But soon as I hit submit it says that the values are null. This code works perfectly with SessionScope.
WARNING: /admin/index.xhtml #104,109 value="#{detailsBean.detailsContact.name}": Target Unreachable, 'null' returned null
javax.el.PropertyNotFoundException: /admin/index.xhtml #104,109 value="#{detailsBean.detailsContact.name}": Target Unreachable, 'null' returned null
I can see that it's calling the EditBean when I select the data table. It then calls it again when I click the submit button.
I encountered the exact same problem than you, and solved it by using the external context (containing GET parameters) instead of f:viewParam.
In your #PostConstruct method, just get your parameter with something like
FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
The lifecycle doesn't allow your approach.
At first, the bean is created ( constructor ). After that, there is executed dependency injection which is followed by #PostConstruct method and after that the JSF file is evaluated. And the viewParam is in that file. So you have to register another listener which is called after filling view params.
I have a solution for #RequestScope beans, but if the bean's scope is longer ( like View ) then this method is executed after each request ( including AJAX ) which is not probably desired.
Use this for request scope beans:
<f:metadata>
<f:viewParam id="id" name="id" value="#{detailsBean.id}"/>
<f:event type="preRenderView" listener="#{detailsBean.onLoad}" />
</f:metadata>
For #ViewScope beans I am using this "hack" which works but probably is not best practise. It does same thing but probably it isn't the correct approach.
#{detailsBean.onLoad()}
<f:metadata>
<f:viewParam id="id" name="id" value="#{detailsBean.id}"/>
</f:metadata>
I hope that this is helpful for you.
EDIT:
you are using a lot of AJAX here. This calls have to land in at least ViewScoped beans. View Scope is similar to RequestScope, but it takes a quite longer - til the page is left.
But I haven't read it all, there is a lot of code and if the ViewScope doesn't help then maybe you should provide the small piece of problematic code to be chance there to find and focus on the real problem.

Categories