Hi trying to call the method on button click, but it doesnt work i also tried onclick instead action it also doesnt work. i couldnt understand where is the mistake please help me
here is my managed bean
package com.primefaces.managedbean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import com.primefaces.domain.KenLocation;
import com.primefaces.service.ILocationService;
#ManagedBean(name = "locationbean")
#ViewScoped
public class LocationBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1101264226039168006L;
/**
*
*/
#ManagedProperty(value = "#{LocationService}")
private ILocationService locationService;
private List<KenLocation> locationList = new ArrayList<KenLocation>();
KenLocation kenLocation;
private String locationName;
private String address1;
private String address2;
private String city;
private String pincode;
private String state;
private String contactNo;
private String organisationName;
#PostConstruct
private void init() {
locationList = locationService.onLoad();
}
public void addnewlocation() {
System.out.println("I am inside newlocation");
kenLocation = new KenLocation();
kenLocation.setLocationName(locationName);
kenLocation.setAddress1(address1);
kenLocation.setAddress2(address2);
kenLocation.setCity(city);
kenLocation.setPincode(Integer.parseInt(pincode));
kenLocation.setPhone(contactNo);
System.out.println(kenLocation);
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getOrganisationName() {
return organisationName;
}
public void setOrganisationName(String organisationName) {
this.organisationName = organisationName;
}
public ILocationService getLocationService() {
return locationService;
}
public void setLocationService(ILocationService locationservice) {
this.locationService = locationservice;
}
public List<KenLocation> getLocationList() {
return locationList;
}
public void setLocationList(List<KenLocation> a_locationList) {
locationList = a_locationList;
}
}
and JSF
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h5>Product List {9 Products can be added per mail}</h5>
<p:separator></p:separator>
<p:growl id="growlLocationtable"></p:growl>
<p:commandButton id="new_location" title="CreateLocation" type="button"
icon="ui-icon-document" onclick="PF('dlg1').show()" />
<p:commandButton id="edit_location" title="EditLocation"
icon=" ui-icon-pencil" />
<p:commandButton id="delete_location" title="DeleteLocation"
icon="ui-icon-trash" />
<h:form id="Locationdataform">
<h:panelGrid columns="2" id="Locationdatatablepanel" resizable="false"
size="600">
<p:dataTable id="Locationdatatable" var="odt"
value="#{locationbean.locationList}">
<p:column headerText="Location Name">
<h:outputText value="#{odt.locationName}" />
</p:column>
<p:column headerText="Address Line1">
<h:outputText value="#{odt.address1}" />
</p:column>
<p:column headerText="Address Line2">
<h:outputText value="#{odt.address2}" />
</p:column>
<p:column headerText="City">
<h:outputText value="#{odt.city}" />
</p:column>
<p:column headerText="Pincode">
<h:outputText value="#{odt.pincode}" />
</p:column>
<p:column headerText="State">
<h:outputText value="#{odt.state}" />
</p:column>
<p:column headerText="Contact No">
<h:outputText value="#{odt.phone}" />
</p:column>
<p:column headerText="Organisation Name">
<h:outputText value="#{odt.ken_Org_ID.name}" />
</p:column>
</p:dataTable>
</h:panelGrid>
</h:form>
<!-- dialog -->
<p:dialog header="Add Location" widgetVar="dlg1" minHeight="40"
modal="true">
<h:form id="addLocationForm">
<h:panelGrid columns="2" id="grid">
<h:outputLabel value="Location Name"></h:outputLabel>
<p:inputText id="txt_Name" value="#{locationbean.locationName}" />
<h:outputLabel value="Address1"></h:outputLabel>
<p:inputText id="txt_address1" value="#{locationbean.address1}" />
<h:outputLabel value="Address2"></h:outputLabel>
<p:inputText id="txt_address2" value="#{locationbean.address2}" />
<h:outputLabel value="City"></h:outputLabel>
<p:inputText id="txt_city" value="#{locationbean.city}" />
<h:outputLabel value="Pincode"></h:outputLabel>
<p:inputText id="txt_pincode" value="#{locationbean.pincode}" />
<h:outputLabel value="State"></h:outputLabel>
<p:inputText id="txt_state" value="#{locationbean.state}" />
<h:outputLabel value="Contactno"></h:outputLabel>
<p:inputText id="txt_contactno" value="#{locationbean.contactNo}" />
<h:outputLabel value="Organistaion name"></h:outputLabel>
<p:inputText id="txt_orgname"
value="#{locationbean.organisationName}" />
<p:commandButton id="addlocatin_btn" value="Save"
action="#{locationbean.addnewlocation}" type="submit" />
</h:panelGrid>
</h:form>
</p:dialog>
Related
i am pretty new to jsf and i'm having a bit trouble implementing a subTable in my dataTable. Der var atribute from my subtable doesn't seem to evaluate to the elements from the list. Also the #PostConstruct method from my backing bean isn't called either, when i execute my webapp and navigate to the xhtml site. No errors are shown in the console, so i have pretty much no idea what i did wrong.
Backing Bean
#Named(value = "selfEvalBean")
#ViewScoped
public class SelfEvaluationBean extends AbstractBean implements Serializable {
private static final long serialVersionUID = 310401011219411386L;
private static final Logger logger = Logger.getLogger(SelfEvaluationBean.class);
#Inject
private ISelfEvaluationManager manager;
private List<SelfEvaluation> selfEvaluations;
private SelfEvaluationTopic topic;
public List<SelfEvaluation> getSelfEvaluations() {
return selfEvaluations;
}
public void setSelfEvaluation(final List<SelfEvaluation> theSelfEvaluations) {
selfEvaluations = theSelfEvaluations;
}
#PostConstruct
public void init() {
if (!isLoggedIn()) {
return;
}
final User user = getSession().getUser();
List<SelfEvaluation> eval = user.getSelfEvaluations();
if (eval == null) {
eval = manager.createSelfEvaluation(user);
}
selfEvaluations = eval;
topic = new SelfEvaluationTopic();
}
//some methods
/**
* #return the topic
*/
public SelfEvaluationTopic getTopic() {
return topic;
}
/**
* #param theTopic
*/
public void setTopic(final SelfEvaluationTopic theTopic) {
topic = theTopic;
}
}
SelEvaluation Class
#Entity
public class SelfEvaluation extends JPAEntity implements Serializable {
private static final long serialVersionUID = 1L;
#ManyToOne
private User user;
#Column
private String title;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<SelfEvaluationTopic> topics = new ArrayList<>();
public User getUser() {
return user;
}
public void setUser(final User theUser) {
user = theUser;
public List<SelfEvaluationTopic> getTopics() {
return topics;
}
public void setTopics(final List<SelfEvaluationTopic> theTopics) {
topics = theTopics;
}
public void addSelfEvalTopic(final SelfEvaluationTopic theTopic) {
topics.add(theTopic);
}
public void removeSelfEvalTopic(final SelfEvaluationTopic theTopic) {
topics.remove(theTopic);
}
#Override
public boolean equals(final Object theObject) {
if (!(theObject instanceof SelfEvaluation)) {
return false;
}
final SelfEvaluation other = (SelfEvaluation) theObject;
return getId().equals(other.getId());
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
#Override
public int hashCode() {
return getId().hashCode();
}
#Override
public String toString() {
return String.format("SelfEvaluation {id: %d, from: %s}", getId(),
user.getUsername());
}
}
SelfEvaluationTopic Class
#Entity
public class SelfEvaluationTopic extends JPAEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Column(nullable = false)
private String topic;
#Column
private boolean sad;
#Column
private boolean normal;
#Column
private boolean happy;
public String getTopic() {
return topic;
}
public void setTopic(final String theTopic) {
topic = assertNotNull(theTopic);
}
public boolean getSad() {
return sad;
}
public void setSad(final boolean evaluation) {
sad = evaluation;
}
public boolean getNormal() {
return normal;
}
public void setNormal(final boolean evaluation) {
normal = evaluation;
}
public boolean getHappy() {
return happy;
}
public void setHappy(final boolean evaluation) {
happy = evaluation;
}
#Override
public boolean equals(final Object theObject) {
if (!(theObject instanceof SelfEvaluationTopic)) {
return false;
}
final SelfEvaluationTopic other = (SelfEvaluationTopic) theObject;
return getId().equals(other.getId());
}
#Override
public int hashCode() {
return getId().hashCode();
}
#Override
public String toString() {
return String
.format("SelfEvaluationTopic {id: %d, topic: %s, sad: %b, normal: %b, happy: %b}",
getId(), topic, sad, normal, happy);
}
}
XHTML Site
<?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://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="templates/template.xhtml">
<!--header and footer template-->
<ui:define name="content">
<f:loadBundle basename="internationalization.selfEval" var="msg" />
<h:form id="form">
<p:growl id="info" autoUpdate="true" />
<p:dataTable id="selfEval" var="eval" value="#{selfEvalBean.selfEvaluations}" >
<f:facet name="header">
#{msg['header']}
</f:facet>
<p:columnGroup type="header">
<p:row>
<p:column>
<f:facet name="header">#{msg['selfEval']}</f:facet>
</p:column>
<p:column width="2%">
<f:facet id="sad" name="header">
<p:graphicImage library="images" name="sad.png"/>
</f:facet>
</p:column>
<p:column width="2%">
<f:facet id="sad" name="header">
<p:graphicImage library="images" name="normal.png"/>
</f:facet>
</p:column>
<p:column width="2%">
<f:facet id="sad" name="header">
<p:graphicImage library="images" name="happy.png"/>
</f:facet>
</p:column>
</p:row>
</p:columnGroup>
<p:subTable var="t" value="#{eval.topics}">
<f:facet name="header">
<h:outputText value="#{eval.title}" />
</f:facet>
<p:column id="topic" >
<h:outputText value="#{t}" /> <!--t is of type List<SelfEvaluation> and not SelfEvaluationTopic-->
<p:commandButton style="float:right; width:22px; height: 22px; background-color: #cd001e;" title="Delete" update=":form" action="#{selfEvalBean.remove(t)}" icon="fa fa-trash-o" />
</p:column>
<p:column width="2%" >
<div style="text-align: center;" >
<p:selectBooleanCheckbox id="s" value="#{t}" />
</div>
</p:column>
<p:column width="2%" >
<div style="text-align: center;" >
<p:selectBooleanCheckbox id="n" value="#{t}" />
</div>
</p:column>
<p:column width="2%" >
<div style="text-align: center;" >
<p:selectBooleanCheckbox id="h" value="#{t}" />
</div>
</p:column>
</p:subTable>
</p:dataTable>
<center>
<p:commandButton id="addSelfEvalTopic" styleClass="button" value="#{msg['actionAdd']}" onclick="PF('evalDialog').show();" update=":form" />
<p:commandButton id="selection" styleClass="button" style="float:right;" value="#{msg['actionSelect']}" action="#{selfEvalBean.save}" />
</center>
</h:form>
<p:dialog widgetVar="evalDialog" header="#{msg['newTopic']}" showEffect="clip" hideEffect="clip" resizable="false">
<h:form id="dialog">
<h:panelGrid columns="2">
<p:outputLabel value="Description:" />
<p:inputText value="#{selfEvalBean.topic.topic}" required="true" maxlength="60" />
<p:commandButton value="#{msg['actionSave']}" styleClass="button" action="#{selfEvalBean.addTopic}" update=":form" oncomplete="PF('evalDialog').hide();" />
<p:commandButton value="#{msg['actionCancel']}" styleClass="button" immediate="true" oncomplete="PF('evalDialog').hide();" />
</h:panelGrid>
</h:form>
</p:dialog>
</ui:define>
</ui:composition>
Manager Class fills the Database with some initial data, so there is nothing really interesting going on.
JSF version is 2.2.12 and PrimeFaces version is 6.0.
I'm using Maven for build and the webapp is running on GlassFish 4.1.1.
the problem I have is that the command button in my dialog doesn't fire the action method in the controller. No logger outputs for the example method "greet". Can anybody look over please and give me hints? What am I doing wrong?
My JSF-Page:
<!DOCTYPE HTML>
<html lang="en" 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:o="http://omnifaces.org/ui"
xmlns:of="http://omnifaces.org/functions">
<f:view id="bestellungLieferantView">
<f:metadata>
<f:event type="preRenderView"
listener="#{camundaTaskForm.startTaskForm()}" />
</f:metadata>
<h:head>
<title>Paket zusammenstellen</title>
</h:head>
<h:body>
<h:form id="bestellungLieferantForm">
<p:dialog id="komponentenAuswahlDialog"
header="Komponenten auswählen" widgetVar="komponentenAuswahlDialog"
modal="true" height="auto" width="auto">
<p:pickList id="komponenteAuswahlPickList"
value="#{bestellungLieferantController.komponentenDualListModel}"
var="komponente" itemLabel="#{komponente.serienNummer}"
converter="entityConverter"
itemValue="#{komponente}" showSourceFilter="true"
showTargetFilter="true">
<f:facet name="sourceCaption">Quelle</f:facet>
<f:facet name="targetCaption">Ziel</f:facet>
</p:pickList>
<p:commandButton process="#this"
action="#{bestellungLieferantController.greet}"
id="auswahlSpeichern" value="Auswahl speichern"
oncomplete="PF('komponentenAuswahlDialog').hide();" />
</p:dialog>
<h:panelGrid id="paketInformationPG" columns="2" border="1">
<f:facet name="header">
<h:outputText value="Paket zusammenstellen" />
</f:facet>
<h:outputLabel value="Kunde:" />
<h:outputText value="#{processVariables['kunde']}" />
<h:outputLabel value="Betriebssystem:" />
<h:outputText value="Platzhalter" />
<h:outputLabel value="Benutzer:" />
<h:outputText value="#{processVariables['benutzerName']}" />
</h:panelGrid>
<h:panelGrid id="komponentenZusammenstellungPG" columns="2"
border="1">
<f:facet name="header">
<h:panelGrid columns="2">
<h:outputText value="Komponenten" />
<p:commandButton id="auswahlKomponenteButton"
action="#{bestellungLieferantController.createAvailableKomponentDualListModel()}"
type="button" onclick="PF('komponentenAuswahlDialog').show();"
value="+" />
</h:panelGrid>
</f:facet>
<p:dataTable id="komponenteTable" widgetVar="komponenteTable"
var="komponente"
value="#{bestellungLieferantController.komponentenList}">
<p:column>
<f:facet name="header">Typ</f:facet>
<h:outputText value="#{komponente.produkt.typ.name}" />
</p:column>
<p:column>
<f:facet name="header">Bezeichnung</f:facet>
<h:outputText value="#{komponente.produkt.name}" />
</p:column>
<p:column>
<f:facet name="header">SN</f:facet>
<h:outputText value="#{komponente.serienNummer}" />
</p:column>
<p:column headerText="Kaufdatum">
<f:facet name="header">Kaufdatum</f:facet>
<h:outputText value="#{komponente.bestellDatum}" />
</p:column>
<p:column>
<f:facet name="header">Aktion</f:facet>
<p:commandLink value="Bearbeiten" />
<p:commandLink value="Enfernen" />
</p:column>
</p:dataTable>
</h:panelGrid>
</h:form>
</h:body>
</f:view>
</html>
My Bean:
#ManagedBean(name="bestellungLieferantController")
#SessionScoped
public class BestellungLieferantController implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2862985625231368306L;
#EJB
private BestellungFacade bestellungFacade;
#EJB
private PaketFacade paketFacade;
#EJB
private KomponenteFacade komponenteFacade;
#EJB
private BetriebssystemFacade betriebssystemFacade;
// Komponent-List with added komponent items
private List<Komponente> komponentenList = new ArrayList<Komponente>();
private DualListModel<Komponente> komponentenDualListModel;
private static final Logger logger = Logger.getLogger(BestellungLieferantController.class);
public DualListModel<Komponente> getKomponentenDualListModel() {
return komponentenDualListModel;
}
public void setKomponentenDualListModel(DualListModel<Komponente> komponentenDualListModel) {
this.komponentenDualListModel = komponentenDualListModel;
}
public List<Komponente> getKomponentenList() {
logger.info("KomponenList-Size: " + this.komponentenList.size());
return komponentenList;
}
public void setKomponentenList(List<Komponente> komponentenList) {
logger.info("Setting a new KomponentenList...");
this.komponentenList = komponentenList;
}
public void greet(){
logger.info("Greet Method Invoked!");
}
/**
* Gets the actual Model with the distinct source and
* #param targetList
* #return
*/
#PostConstruct
public void createAvailableKomponentDualListModel(){
// Logger
logger.info("CreateAvailableKomponentDualList invoked!");
List<Komponente> sourceKomponenteList = this.komponenteFacade.getAllAvailableKomponente();
List<Komponente> sourceKomponenteDistinctList = new ArrayList<Komponente>();
if (this.komponentenList.size() != 0){
for(Komponente k : sourceKomponenteList){
if (!komponentenList.contains(k)){
sourceKomponenteDistinctList.add(k);
}
}
} else {
sourceKomponenteDistinctList = sourceKomponenteList;
}
// komponentenDualListModel.setSource(sourceKomponenteDistinctList);
// komponentenDualListModel.setTarget(komponentenList);
this.setKomponentenDualListModel(new DualListModel<Komponente>());
this.getKomponentenDualListModel().setSource(sourceKomponenteDistinctList);
this.getKomponentenDualListModel().setTarget(this.komponentenList);
}
public void putSelectionIntoKomponenteList(){
logger.info("PutSelectionIntoKomponentList");
logger.info("KOMPONENTELIST: " + komponentenDualListModel.getTarget());
this.komponentenList = this.komponentenDualListModel.getTarget();
}
}
My Converter:
#FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {
// Checking the converter
private static final Logger logger = Logger.getLogger(EntityConverter.class);
private static Map<Object, String> entities = new WeakHashMap<Object, String>();
#Override
public String getAsString(FacesContext context, UIComponent component, Object entity) {
synchronized (entities) {
logger.info("[Converter] GetAsString: " + ", Class:" + entity.getClass() + ", Component-ID: " + component.getId());
if (!entities.containsKey(entity)) {
String uuid = UUID.randomUUID().toString();
entities.put(entity, uuid);
return uuid;
} else {
return entities.get(entity);
}
}
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
logger.info("[Converter] GetAsString: " + ", UUID:" + uuid + ", Component-ID: " + component.getId());
for (Entry<Object, String> entry : entities.entrySet()) {
if (entry.getValue().equals(uuid)) {
return entry.getKey();
}
}
//return uuid;
return null;
}
}
you need actionListener attribute instead of action in your p:commandbutton tag. and Also use #ViewScoped instead of #SessionScoped in your backing bean. and add ajax="false" in p:commandButton
I'm trying to use a Primefaces dialog to insert an entity object in a database, it works the first time I use the dialog, the keeps the same bean inside the dialog when I try to use it the second time, here is my code:
this is in the file index.xhtml I have a table called patients and this is the footer:
<f:facet name="footer">
<p:outputPanel>
<p:growl id="growl" showDetail="true" />
<p:commandButton value="Add Patient" icon="ui-icon-extlink"
actionListener="#{patientsViewBean.addNewPatientDialog}">
<p:ajax event="dialogReturn"
listener="#{patientsViewBean.onDialogReturn}" update="patients" />
</p:commandButton>
</p:outputPanel>
</f:facet>
the dialog page is addNewDialog.xhtml it contains:
<!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://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add New Patient</title>
<style type="text/css">
.ui-widget {
font-size: 80%;
}
</style>
</h:head>
<h:body>
<p:panel style="margin: 2px;">
<h:form id="form" >
<p:growl id="msgs" showDetail="true" />
<p:panel title="Patient Personal Information" header="Patient Personal Information">
<p:panelGrid style="margin: 2px 2px 2px 2px" columns="2"
columnClasses="label, value">
<p:outputLabel value="First Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.firstName}"
required="true" label="First Name"></p:inputText>
<p:outputLabel value="Father Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.fatherName}"
required="true" label="Father Name"></p:inputText>
<p:outputLabel value="Family Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.familyName}"
required="true" label="Family Name"></p:inputText>
<p:outputLabel value="Mother Name: *"></p:outputLabel>
<p:inputText value="#{newPatientView.patient.motherName}"
required="true" label="Mother Name"></p:inputText>
<p:outputLabel value="Birth Date"></p:outputLabel>
<p:calendar id="bdate" value="#{newPatientView.patient.birthDate}"
locale="ar" navigator="true" yearRange="c-120:c" effect="fade"
mask="true" pattern="yyyy-MM-dd" required="true" />
<p:outputLabel value="Birth Place: "></p:outputLabel>
<p:inputText value="#{newPatientView.patient.birthPlace}"
required="false" label="Birth Place"></p:inputText>
</p:panelGrid>
</p:panel>
<p:panel title="Contact Information" header="Contact Information">
<p:remoteCommand name="updateButtonsStatus"
process="#this contactInfoTable:buttons"
update="contactInfoTable:buttons"></p:remoteCommand>
<p:dataTable id="contactInfoTable" var="cntctInfo"
selectionMode="single" rowKey="#{cntctInfo}"
selection="#{newPatientView.cntctInfo}"
value="#{newPatientView.patient.contactInfoList}" editable="true"
widgetVar="cellCntctInfo">
<p:ajax event="rowEditInit"
listener="#{newPatientView.onRowEditInit}"
oncomplete="updateButtonsStatus()" />
<p:ajax event="rowEdit" immediate="true"
listener="#{newPatientView.onRowEdit}" update=":form:msgs"
oncomplete="updateButtonsStatus()" />
<p:ajax event="rowEditCancel"
listener="#{newPatientView.onRowCancel}"
oncomplete="updateButtonsStatus()" />
<p:column headerText="Email">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cntctInfo.email}" />
</f:facet>
<f:facet name="input">
<p:inputText id="emailInput" value="#{cntctInfo.email}"
style="width:95%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Phone">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cntctInfo.phone}" />
</f:facet>
<f:facet name="input">
<p:inputText id="phoneInput" value="#{cntctInfo.phone}"
style="width:95%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Type">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{cntctInfo.type}" />
</f:facet>
<f:facet name="input">
<p:selectOneMenu id="typeInput" value="#{cntctInfo.type}"
style="width:100%; height: 95%">
<f:selectItem itemLabel="Main" itemValue="Main"></f:selectItem>
<f:selectItem itemLabel="Home" itemValue="Home"></f:selectItem>
<f:selectItem itemLabel="Work" itemValue="Work"></f:selectItem>
<f:selectItem itemLabel="Perm" itemValue="Perm"></f:selectItem>
<f:selectItem itemLabel="Curr" itemValue="Curr"></f:selectItem>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Edit" style="width:32px">
<p:rowEditor />
</p:column>
<f:facet name="footer">
<p:outputPanel id="buttons" autoUpdate="true">
<p:commandButton value="Add New" process="#this contactInfoTable"
actionListener="#{newPatientView.onAddNewContactInfo}"
update="contactInfoTable :form:msgs"
disabled="#{newPatientView.addContactInfoDisabled}" />
<p:commandButton value="Delete Seleced"
process="#this contactInfoTable"
actionListener="#{newPatientView.onDeleteSelectedContactInfo}"
update="contactInfoTable :form:msgs"
disabled="#{newPatientView.deleteSelectedContactInfoDisabled}" />
</p:outputPanel>
</f:facet>
</p:dataTable>
</p:panel>
<p:panel>
<p:commandButton value="Save" actionListener="#{newPatientView.onDialogApprove}"></p:commandButton>
<p:commandButton value="Discard" actionListener="#{newPatientView.onDialogCancel}"></p:commandButton>
</p:panel>
</h:form>
</p:panel>
</h:body>
</html>
I have two baking beans newPatientView with this code:
package me.bttb.crs.beans.patient;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import org.primefaces.event.RowEditEvent;
import me.bttb.crs.model.ContactInfo;
import me.bttb.crs.model.Ptnt;
#Named
#ManagedBean
#ViewScoped
public class NewPatientView {
#Inject
private PatientDAO patientDAO;
private Ptnt patient;
private List<ContactInfo> cntctInfoList;
private ContactInfo cntctInfo;
private boolean addContactInfoDisabled = false;
private boolean deleteSelectedContactInfoDisabled = true;
boolean confirm = false;
public NewPatientView() {
init();
}
public void init() {
this.setPatient(new Ptnt());
this.setCntctInfoList(new ArrayList<>());
this.getPatient().setContactInfoList(this.getCntctInfoList());
}
/////////////// EVENTS//////////////////
public void onAddNewContactInfo(ActionEvent event) {
if (patient.getContactInfoList() == null)
patient.setContactInfoList(new ArrayList<>());
boolean hasNewRow = patient.getContactInfoList().stream()
.filter(ci -> ci.getEmail() == null && ci.getPhone() == null).count() >= 1;
if (hasNewRow) {
FacesMessage msg = new FacesMessage("Can't add new row", "There is an empty row already!!");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
ContactInfo cntctInfo = new ContactInfo();
cntctInfo.setType("Main");
cntctInfo.setPrsn(patient);
patient.getContactInfoList().add(cntctInfo);
}
}
public void onDeleteSelectedContactInfo(ActionEvent event) {
if (cntctInfo != null) {
cntctInfoList.remove(cntctInfo);
cntctInfo = null;
}
this.setDeleteSelectedContactInfoDisabled(true);
this.setAddContactInfoDisabled(false);
}
public void onRowEdit(RowEditEvent event) {
this.setDeleteSelectedContactInfoDisabled(true);
this.setAddContactInfoDisabled(false);
ContactInfo editedContactInfo = (ContactInfo) event.getObject();
boolean moreThanOne = patient.getContactInfoList().stream().filter(ci -> ci.equals(editedContactInfo))
.count() > 1;
if (moreThanOne) {
patient.getContactInfoList().remove(editedContactInfo);
FacesMessage msg = new FacesMessage("Row Removed", "The contact information provided is redundent!!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
public void onRowEditInit(RowEditEvent event) {
if (event.getObject() instanceof ContactInfo) {
this.setCntctInfo((ContactInfo) event.getObject());
this.setDeleteSelectedContactInfoDisabled(false);
}
this.setAddContactInfoDisabled(true);
}
public void onRowCancel(RowEditEvent event) {
this.setDeleteSelectedContactInfoDisabled(true);
this.setAddContactInfoDisabled(false);
}
public void onDialogCancel() {
RequestContext.getCurrentInstance().closeDialog(null);
}
public void onDialogApprove() {
RequestContext.getCurrentInstance().closeDialog(patient);
}
public PatientDAO getPatientDAO() {
return patientDAO;
}
public void setPatientDAO(PatientDAO patientDAO) {
this.patientDAO = patientDAO;
}
public Ptnt getPatient() {
return patient;
}
public void setPatient(Ptnt patient) {
this.patient = patient;
}
public ContactInfo getCntctInfo() {
return cntctInfo;
}
public void setCntctInfo(ContactInfo cntctInfo) {
this.cntctInfo = cntctInfo;
}
public boolean isAddContactInfoDisabled() {
return addContactInfoDisabled;
}
public void setAddContactInfoDisabled(boolean addContactInfoDisabled) {
this.addContactInfoDisabled = addContactInfoDisabled;
}
public boolean isDeleteSelectedContactInfoDisabled() {
return deleteSelectedContactInfoDisabled;
}
public void setDeleteSelectedContactInfoDisabled(boolean deleteSelectedContactInfoDisabled) {
this.deleteSelectedContactInfoDisabled = deleteSelectedContactInfoDisabled;
}
public List<ContactInfo> getCntctInfoList() {
return cntctInfoList;
}
public void setCntctInfoList(List<ContactInfo> cntctInfoList) {
this.cntctInfoList = cntctInfoList;
}
}
and here is how I call the dialog in patienViewBean:
package me.bttb.crs.beans.patient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import me.bttb.crs.model.Ptnt;
#Named
#ManagedBean
#ViewScoped
public class PatientsViewBean {
#Autowired
private PatientDAO patientDAO;
private List<Ptnt> patients;
private List<Ptnt> filterdPatients;
public PatientsViewBean() {
}
public long getPatientsCount() {
return patientDAO.getPatientsCount();
}
public List<Ptnt> refreshAllPatients() {
this.setPatients(patientDAO.getPatients());
return this.getPatients();
}
public void addNewPatientDialog() {
Map<String, Object> options = new HashMap<String, Object>();
options.put("resizable", false);
options.put("draggable", false);
options.put("modal", true);
//options.put("contentHeight", "95%");
//options.put("height", 400);
//options.put("width", 700);
options.put("closable", false);
RequestContext.getCurrentInstance().openDialog("newPatientDialog", options, null);
}
public void onDialogReturn(SelectEvent event) {
if (event.getObject() != null && event.getObject() instanceof Ptnt) {
patientDAO.addpatient((Ptnt) event.getObject());
refreshAllPatients();
FacesMessage msg = new FacesMessage("Patient Added", "Pateint information added in the database.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("operation canceld", "Nothing is saved to the database.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
////////////////////////////////////
public PatientDAO getPatientDAO() {
return patientDAO;
}
public void setPatientDAO(PatientDAO patientDAO) {
this.patientDAO = patientDAO;
}
public List<Ptnt> getPatients() {
return patients;
}
public void setPatients(List<Ptnt> patients) {
this.patients = patients;
}
public List<Ptnt> getFilterdPatients() {
return filterdPatients;
}
public void setFilterdPatients(List<Ptnt> filterdPatients) {
this.filterdPatients = filterdPatients;
}
}
what am I doing wrong, shouldn't the newPatientView get recreated every time the dialog shows up??
please explain the life cycle of the view here.
I have a little probleme with primefaces dataTable,
i have set a commandButton inside my table inorder to delete data from the table
but whene i choose to delete a row i found that it had deleted 2 rows not just one
this is my Bean
package com.beans;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import com.bo.DiplomeBo;
import com.converter.DiplomeDataModel;
import com.model.Collaborateur;
import com.model.Diplome;
public class DiplomeBean {
public Integer idDiplome;
public String ecole;
public String typeEcole;
public String typeDiplome;
public Integer promotion;
private Set<Collaborateur> collaborateurs = new HashSet<Collaborateur>(0);
public Diplome selectedDiplome;
private DiplomeBo diplomeBo;
public Diplome getSelectedDiplome() {
return selectedDiplome;
}
public void setSelectedDiplome(Diplome selectedDiplome) {
this.selectedDiplome = selectedDiplome;
}
public Integer getIdDiplome() {
return idDiplome;
}
public void setIdDiplome(Integer idDiplome) {
this.idDiplome = idDiplome;
}
public String getEcole() {
return ecole;
}
public void setEcole(String ecole) {
this.ecole = ecole;
}
public String getTypeEcole() {
return typeEcole;
}
public void setTypeEcole(String typeEcole) {
this.typeEcole = typeEcole;
}
public Integer getPromotion() {
return promotion;
}
public void setPromotion(Integer promotion) {
this.promotion = promotion;
}
public Set<Collaborateur> getCollaborateurs() {
return collaborateurs;
}
public void setCollaborateurs(Set<Collaborateur> collaborateurs) {
this.collaborateurs = collaborateurs;
}
public void setDiplomeBo(DiplomeBo diplomeBo) {
this.diplomeBo = diplomeBo;
}
public String getTypeDiplome() {
return typeDiplome;
}
public void setTypeDiplome(String typeDiplome) {
this.typeDiplome = typeDiplome;
}
public String AddDiplome() {
Diplome diplome = new Diplome();
diplome.setEcole(getEcole());
diplome.setPromotion(getPromotion());
diplome.setTypeDiplome(getTypeDiplome());
diplome.setTypeEcole(getTypeEcole());
diplomeBo.addDiplome(diplome);
clearForm();
return "Ajout Bien Fait !!";
}
public String UpdateDiplome(Diplome dip) {
diplomeBo.updateDiplome(dip);
return "Update Bien Fait";
}
public String DeleteDiplome(Diplome diplome){
diplomeBo.deleteDiplome(diplome);
clearForm();
return "";
}
public List<Diplome> getAllDiplome() {
return diplomeBo.findAllDiplome();
}
private void clearForm() {
this.setEcole("");
this.setPromotion(0);
this.setTypeEcole("");
this.setTypeEcole("");
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Diplome Edited");
Integer i = ((Diplome) (event.getObject())).getIdDiplome();
Diplome d = new Diplome();
d.setIdDiplome(i);
d.setEcole(this.getEcole());
this.UpdateDiplome(d);
FacesContext.getCurrentInstance().addMessage(null, msg);
clearForm();
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Diplome Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
this is my 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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<body>
<f:view>
<h:outputLink value="Admin/default.xhtml">Go to your app</h:outputLink>
<h:form id="form">
<p:growl id="messages" showDetail="true" />
<p:dataTable var="dip" value="#{diplome.getAllDiplome()}" id="diplomeList"
editable="true">
<f:facet name="header">
In-Cell Editing
</f:facet>
<p:ajax event="rowEdit" listener="#{diplome.onEdit}"
/>
<p:ajax event="rowEditCancel" listener="#{diplome.onCancel}"
/>
<p:column headerText="ID" style="width:10%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{dip.idDiplome}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{dip.idDiplome}#{diplome.idDiplome}" style="width:100%" readonly="true" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Ecole" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{dip.ecole}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{diplome.ecole}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:6%">
<p:rowEditor />
</p:column>
<p:column>
<p:commandButton icon="ui-icon-trash"
title="Delete this actor"
action="#{diplome.DeleteDiplome(dip)}"
ajax="false" />
</p:column>
</p:dataTable>
</h:form>
</f:view>
</body>
</html>
I have the following files in my application but I can't get the values from the selectOneMenu on file elementoUpdateDialog.xhtml to update the dataTable on gerirElementos.xhtml and sql table.
Where is my error?
elementoUpdateDialog.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:body>
<p:dialog widgetVar="elementoUpdateDialogWidget"
id="elementoUpdateDialogId" height="300" width="500" modal="true"
closable="true" draggable="false" resizable="false">
<h:form id="elementoUpdateDialogForm" prependId="false">
<h:panelGrid columns="2">
<h:outputText value="elementoID" />
<h:inputText value="#{elementoMB.elemento.elementoId}"
required="true" label="elementoID" />
<h:outputText value="Posto" />
<h:outputText value="#{elementoMB.elemento.posto.postoId}" />
<h:selectOneMenu value="#{postoMB.posto.postoId}">
<f:selectItems value="#{postoMB.allPostos}" var ="posto"
itemLabel="#{postoMB.posto.posto}" itemValue="# {elementoMB.elemento.posto.postoId}"/>
</h:selectOneMenu>
<br />
<h:outputText value="Classe" />
<h:outputText value="#{elementoMB.elemento.classe.classeId}" />
<h:selectOneMenu value="# {elementoMB.elemento.classe.classeId}">
<f:selectItems value="#{classeMB.allClasses}"/>
<f:selectItem itemValue="# {elementoMB.elemento.classe.classeId}" itemLabel="#{elementoMB.elemento.classe.classeId}"/>
</h:selectOneMenu>
<br/>
<h:outputText value="Nome" />
<h:inputText value="#{elementoMB.elemento.nome}" required="true"
label="Nome" />
<h:outputText value="NII" />
<h:inputText value="#{elementoMB.elemento.NII}" required="true"
label="NII" />
<p:commandButton value="Gravar" icon="ui-icon-plus"
action="#{elementoMB.updateElemento()}"
update=":messageGrowl :elementosForm:elementosTable"
oncomplete="closeDialogIfSucess(xhr, status, args, elementoUpdateDialogWidget, 'elementoUpdateDialogId')" />
<p:commandButton value="Cancelar" icon="ui-icon-cancel"
actionListener="#{elementoMB.resetElemento()}"
onclick="elementoUpdateDialogWidget.hide();" type="button" />
</h:panelGrid>
</h:form>
</p:dialog>
</h:body>
</html>
gerirElementos.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<ui:composition template="/pages/protected/templates/master.xhtml">
<ui:define name="divMain">
<p:menubar>
<p:submenu label="Elementos" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/defaultUser/gerirElementos.xhtml" />
</p:submenu>
<p:submenu label="Classes" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/admin/gerirClasses.xhtml" />
</p:submenu>
<p:submenu label="Postos" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/admin/gerirPostos.xhtml" />
</p:submenu>
<p:submenu label="RegistoSarPerm" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/defaultUser/gerirRegistoSarPerm.xhtml" />
</p:submenu>
</p:menubar>
<h:form id="elementosForm">
<p:dataTable id="elementosTable" var="elemento"
value="#{elementoMB.allElementos}" paginator="true" rows="10"
selepaginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="1,5,10">
<f:facet name="header">
Lista de Elementos
</f:facet>
<p:column headerText="NII" sortBy="nii" id="nii">
#{elemento.NII}
</p:column>
<p:column headerText="Posto" sortBy="posto" id="posto">
#{elemento.posto.posto}
</p:column>
<p:column headerText="Classe" sortBy="classe" id="classe">
#{elemento.classe.classe}
</p:column>
<p:column headerText="Nome" sortBy="nome" id="nome">
#{elemento.nome}
</p:column>
<p:column>
<p:spacer width="10px" />
<p:commandButton value="Editar" icon="ui-icon-pencil"
update=":elementoUpdateDialogForm"
onclick="elementoUpdateDialogWidget.show();">
<f:setPropertyActionListener target="#{elementoMB.elemento}"
value="#{elemento}" />
</p:commandButton>
<p:spacer width="10px" />
<p:commandButton value="Eliminar" icon="ui-icon-trash"
update=":elementoDeleteDialogForm"
onclick="elementoDeleteDialogWidget.show();">
<f:setPropertyActionListener target="#{elementoMB.elemento}"
value="#{elemento}" />
</p:commandButton>
<p:spacer width="10px" />
</p:column>
</p:dataTable>
<p:commandButton value="Novo Elemento" icon="ui-icon-plus"
actionListener="#{elementoMB.resetElemento()}"
onclick="elementoCreateDialogWidget.show();" />
</h:form>
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoCreateDialog.xhtml" />
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoUpdateDialog.xhtml" />
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoDeleteDialog.xhtml" />
</ui:define>
</ui:composition>
</h:body>
</html>
Elemento.java
package com.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="Elemento")
public class Elemento implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="elementoId")
private int elementoId;
#ManyToOne
#JoinColumn(name = "classeId")
private Classe classe;
#ManyToOne
#JoinColumn(name="postoID")
private Posto posto;
#Column(name="NII")
private String NII;
#Column(name="nome")
private String nome;
public Elemento(){
}
public Elemento(String NII, String nome){
this.NII = NII;
this.nome = nome;
}
//Getters and Setters
public int getElementoId() {
return elementoId;
}
public void setElementoId(int elementoId) {
this.elementoId = elementoId;
}
public String getNII() {
return NII;
}
public void setNII(String nII) {
NII = nII;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Classe getClasse() {
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public Posto getPosto() {
return posto;
}
public void setPosto(Posto posto) {
this.posto = posto;
}
#Override
public int hashCode() {
return elementoId;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Elemento) {
Elemento elemento = (Elemento) obj;
return elemento.getElementoId() == elementoId;
}
return false;
}
}
ElementoMB.java
package com.mb;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.facade.ElementoFacade;
import com.model.Classe;
import com.model.Elemento;
import com.model.Posto;
#ViewScoped
#ManagedBean
public class ElementoMB extends AbstractMB implements Serializable {
private static final long serialVersionUID = 1L;
private Posto posto;
private Classe classe;
private Elemento elemento;
private List<Elemento> elementos;
private ElementoFacade elementoFacade;
public void createElemento() {
try {
getElementoFacade().createElemento(elemento);;
closeDialog();
displayInfoMessageToUser("Created With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public void updateElemento() {
try {
getElementoFacade().updateElemento(elemento);
closeDialog();
displayInfoMessageToUser("Updated With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public void deleteElemento() {
try {
getElementoFacade().deleteElemento(elemento);
closeDialog();
displayInfoMessageToUser("Deleted With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public List<Elemento> getAllElementos(){
if (elementos == null){
loadElementos();
}
return elementos;
}
public ElementoFacade getElementoFacade() {
if (elementoFacade == null) {
elementoFacade = new ElementoFacade();
}
return elementoFacade;
}
public Elemento getElemento() {
if (elemento == null) {
elemento = new Elemento();
}
return elemento;
}
public void setElemento(Elemento elemento) {
this.elemento = elemento;
}
private void loadElementos() {
elementos = getElementoFacade().listAll();
}
public void resetElemento() {
elemento = new Elemento();
}
public Posto getPosto() {
if (posto == null){
posto = new Posto();
}
return posto;
}
public void setPosto(Posto posto) {
this.posto = posto;
}
public Classe getClasse() {
if (classe == null) {
classe = new Classe();
}
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public void resetClasse() {
classe = new Classe();
}
}
ElementoFacade.java
package com.facade;
import java.io.Serializable;
import java.util.List;
import com.dao.ElementoDAO;
import com.model.Elemento;
public class ElementoFacade implements Serializable {
private static final long serialVersionUID = 1L;
private ElementoDAO elementoDAO = new ElementoDAO();
public void createElemento(Elemento elemento) {
elementoDAO.beginTransaction();
elementoDAO.save(elemento);
elementoDAO.commitAndCloseTransaction();
}
public void updateElemento(Elemento elemento) {
elementoDAO.beginTransaction();
Elemento persistedElemento = elementoDAO.find(elemento.getElementoId());
persistedElemento.setNome(elemento.getNome());
persistedElemento.setNII(elemento.getNII());
elementoDAO.commitAndCloseTransaction();
}
public void deleteElemento(Elemento elemento){
elementoDAO.beginTransaction();
Elemento persistedElementoWithIdOnly = elementoDAO.findReferenceOnly(elemento.getElementoId());
elementoDAO.delete(persistedElementoWithIdOnly);
elementoDAO.commitAndCloseTransaction();
}
public Elemento findElemento(int elementoId) {
elementoDAO.beginTransaction();
Elemento elemento = elementoDAO.find(elementoId);
elementoDAO.closeTransaction();
return elemento;
}
public List<Elemento> listAll() {
elementoDAO.beginTransaction();
List<Elemento> result = elementoDAO.findAll();
elementoDAO.closeTransaction();
return result;
}
}
Here,
<f:selectItems value="#{postoMB.allPostos}" var="posto"
itemLabel="#{postoMB.posto.posto}" itemValue="#{elementoMB.elemento.posto.postoId}"/>
Your itemLabel and itemValue attributes, representing the current option label and value, are wrong. They're for some unclear reason referencing a backing bean property instead of the currently iterated option object as definied in var="posto".
Fix it accordingly:
<f:selectItems value="#{postoMB.allPostos}" var="posto"
itemLabel="#{posto.postoId}" itemValue="#{posto}"/>
This should display the items correctly.
And here,
<h:selectOneMenu value="#{postoMB.posto.postoId}">
the selected item is wrong. This would only cause problems during submitting and during displaying a preselected item. You should refer the very same type as itemValue itself, not some ID (otherwise you're changing only the id of an entity instead of the entity itself, resulting in major potential trouble as those are references):
<h:selectOneMenu value="#{postoMB.posto}">
Supply if necessary a converter in case you don't have a #FacesConverter(forClass=Posto.class).
Apply the same lesson learnt on the other <h:selectOneMenu> you've there.
See also:
Our <h:selectOneMenu> wiki page
How to populate options of h:selectOneMenu from database?