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.
Related
I'm trying get a value from a p:inputText is inside a p:dialog but this is returning null to my bean.
The inputText motivoCancelamento needs to be filled with the content of my inputText motivoCancelamentoDialog inside the dialog.
The another ones are ok, like status, protocoloCancelamento and dataCancelamento.
Can anyone help me?
<h:form id="form">
<p:toolbar>
<f:facet name="left">
<p:growl id="messages" showDetail="true"/>
<p:dialog header="Cancelar Nota" widgetVar="cancelamentoDialog" focus="motivoCancelamentoDialog">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="motivoCancelamentoDialog" value="Motivo Cancelamento:" />
<p:inputText id="motivoCancelamentoDialog" value="#{notaProdutoBean.notaProduto.motivoCancelamento}" />
<p:commandButton value="Cancelar" actionListener="#{notaProdutoBean.cancelarNota()}" update="status motivoCancelamento protocoloCancelamento dataCancelamento messages form"/>
</h:panelGrid>
</p:dialog>
<p:confirmDialog global="true" showEffect="fade" hideEffect="fade">
<p:commandButton value="Sim" type="button" styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />
<p:commandButton value="Não" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close" />
</p:confirmDialog>
</p:toolbar>
<p:fieldset id='panelNotaFiscal' legend="NotaFiscal" >
<p:panelGrid columns="6" columnClasses="centered">
<p:outputLabel for='status' value='Status'/>
<p:inputText id="status" value="#{notaProdutoBean.notaProduto.status}" required="true" requiredMessage="O campo Status é obrigatório">
<p:message for="status"/>
</p:inputText>
<p:outputLabel for="motivoCancelamento" value="Motivo Cancelamento"/>
<p:inputText id="motivoCancelamento" size="25" value="#{notaProdutoBean.notaProduto.motivoCancelamento}">
<p:message for="motivoCancelamento"/>
</p:inputText>
<p:outputLabel for="protocoloCancelamento" value="Protocolo Cancelamento"/>
<p:inputText id="protocoloCancelamento" size="15" value="#{notaProdutoBean.notaProduto.protocoloCancelamento}">
<p:message for="protocoloCancelamento"/>
</p:inputText>
<p:outputLabel for="dataCancelamento" value="Data Cancelamento"/>
<p:calendar id="dataCancelamento" value="#{notaProdutoBean.notaProduto.dataCancelamento}" pattern="dd/MM/yyyy HH:mm:ss">
<p:message for='dataCancelamento'/>
</p:calendar>
</p:panelGrid>
</p:fieldset>
public void cancelarNota(){
try{
if(getNotaProduto().getStatus().equals("Autorizada")){
getNotaProduto().setStatus("Cancelada");
System.out.println("Motivo " + getNotaProduto().getMotivoCancelamento());
getNotaProduto().setProtocoloCancelamento("22222222222222");
getNotaProduto().setDataCancelamento(new Date());
new BaseBean().salvar(getNotaProduto());
RequestContext.getCurrentInstance().execute("PF('cancelamentoDialog').hide();");
}
else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO ,"Mensagem: ", "A nota não está autorizada portanto não pode ser cancelada"));
}
}
catch(Exception e){
new Log().salvaErroLog(e);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR ,"Mensagem: ", "Um erro ocorreu, entre em conto com o adminstrador"));
}
}
You have 2 inputs for the same field in the same form:
<p:inputText id="motivoCancelamentoDialog" value="#{notaProdutoBean.notaProduto.motivoCancelamento}" />
<p:inputText id="motivoCancelamento" size="25" value="#{notaProdutoBean.notaProduto.motivoCancelamento}">
<p:message for="motivoCancelamento"/>
</p:inputText>
you should put the dialog in a separate form so it doesnt post the second input.
also you can specify the elements to process in the "cancelar" button
<p:inputText id="motivoCancelamentoDialog" value="# notaProdutoBean.notaProduto.motivoCancelamento}" />
<p:commandButton value="Cancelar" actionListener="#{notaProdutoBean.cancelarNota()}" update="status motivoCancelamento protocoloCancelamento dataCancelamento messages form" process="#this, motivoCancelamentoDialog"/>
your input tag is actually empty tag
<p:inputText id="motivoCancelamentoDialog" value="#{notaProdutoBean.notaProduto.motivoCancelamento}" />
try using something like below to see if it works.
<p:inputText id="motivoCancelamentoDialog" value="#{notaProdutoBean.notaProduto.motivoCancelamento}">abc</p:inputText>
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;
}
#ManagedBean(name = "menuCtrl")
#ApplicationScoped
public class MenuControleur extends AbstractControleur implements Serializable {
private static final Logger log = Logger.getLogger(ApplicationControleur.class);
private PanierBeans[] selectedRep;
public PanierBeans[] getSelectedRep() {
return selectedRep;
}
public void setSelectedRep(PanierBeans[] selectedRep) {
this.selectedRep = selectedRep;
}
// cache
private List<Spectacle> spectacles;
private List<Representation> representations;
private Spectacle specSelec = new Spectacle();
private List<Artiste> artistes;
private List<Representation> representationsFiltrees;
private List lignesSelec;
public List getLignesSelec() {
return lignesSelec;
}
public void setLignesSelec(List lignesSelec) {
this.lignesSelec = lignesSelec;
}
and in the facelet i have this table
<p:dataTable id="dataTable" var="rep" value="#{menuCtrl.specSelec.representations}" widgetVar="representationsTable"
emptyMessage="Pas de représentation trouvée avec les criteres précisés" filteredValue="#{menuCtrl.representationsFiltrees}" paginator="true" rows="10"
style="background: none" >
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search all fields:" />
<p:inputText id="globalFilter" onkeyup="representationsTable.filter()" style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column id="photoArtiste" headerText="Artiste" >
<ui:param name="imgPath" value="images:#{menuCtrl.specSelec.artiste.lienPhoto}.png" />
<p:graphicImage value="#{resource[imgPath]}" />
</p:column>
<p:column id="nomArtiste" filterBy="#{rep}"
headerText="Artiste"
filterMatchMode="contains">
<h:outputText value="#{menuCtrl.specSelec.artiste.nom}" />
</p:column>
<p:column id="nomSpectacle" filterBy="#{rep}"
headerText="Spectacle"
filterMatchMode="contains">
<h:outputText value="#{menuCtrl.specSelec.nomSpectacle}" />
</p:column>
<p:column id="addColumn" filterBy="#{rep.adresse}"
headerText="Ville" footerText="contains"
filterMatchMode="contains">
<h:outputText value="#{rep.salle.adresseSalle}" />
</p:column>
<p:column id="dateDebutColumn" headerText="Date" footerText="startsWith">
<h:outputText value="#{rep.dateDebut}"
id="popupDate">
<f:convertDateTime pattern="d/M/yyyy" />
</h:outputText>
</p:column>
<p:column id="dispColumn"
headerText="Disponibilité">
<p:inputText id="champDisBillets" value="100" size="5" readonly="true" />
</p:column>
<p:column id="qteBillets"
headerText="Qte Billets">
<p:selectOneMenu value="#{buttonBean.number}">
<f:selectItem itemLabel="1" itemValue="1" />
<f:selectItem itemLabel="2" itemValue="2" />
<f:selectItem itemLabel="3" itemValue="3" />
<f:selectItem itemLabel="4" itemValue="4" />
<f:selectItem itemLabel="5" itemValue="5" />
<f:selectItem itemLabel="6" itemValue="6" />
</p:selectOneMenu>
</p:column>
<p:calendar value="#{calendarBean.date2}" id="popupCal" />
<p:column id="priceColumn" filterBy="#{rep}"
headerText="Prix" footerText="contains"
filterMatchMode="contains">
<p:inputText id="prixBillets" value="#{rep.prix}" readonly="true" size="5"/>
</p:column>
</p:dataTable>
nom i want to add checkboxes but in that case i would have to add a selection attributes that point to one of the managed bean attributes, thing is the rows are populated with differents inds of objects so what type o object should in selection ?
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
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.