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.
Related
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
The problem is that overridden method load() in my LazyDataModel implementation is being called twice every time I try to filter the table.
My LazyDataModel implementation:
public class LazyPostDataModel extends LazyDataModel<Post> {
private List<Post> data;
private final PostService postService;
public LazyPostDataModel(PostService postService) {
this.postService = postService;
data = new ArrayList<>();
}
#Override
public Post getRowData(String rowKey) {
Long id = Long.valueOf(rowKey);
for (Post p : data) {
if (p.getId().equals(id))
return p;
}
return null;
}
#Override
public Object getRowKey(Post post) {
return post.getId();
}
#Override
public List<Post> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
PostFilter filter = new PostFilter(filters, first, pageSize);
FilteredDataModel<Post> postDataModel = postService.findFilteredList(filter);
data = postDataModel.getData();
this.setRowCount(postDataModel.getCount().intValue());
return data;
}
}
My xhtml 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:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition>
<p:panel header="Posts to Review">
<ui:include src="ModerationPostContextMenu.xhtml" />
<p:dataTable id="ModerationPostTable" value="# {moderationPostController.posts}" var="post" lazy="true" rows="25" widgetVar="ModerationPostTable"
paginator="true" rowKey="#{post.id}" selectionMode="single" selection="#{moderationPostController.selected}"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}" >
<p:ajax event="rowSelect" update="#form:contextMenu" />
<p:ajax event="rowUnselect" update="#form:contextMenu" />
<p:column headerText="Id">
<h:outputText value="#{post.id}"/>
</p:column>
<p:column headerText="Creation Date">
<h:outputText value="#{post.creationDate}"/>
</p:column>
<p:column headerText="Author Id">
<h:outputText value="#{post.author.id}"/>
</p:column>
<p:column headerText="Author Nickname">
<h:outputText value="#{post.author.nickname}"/>
</p:column>
<p:column headerText="Text">
<h:outputText value="#{post.text}" />
</p:column>
<p:column headerText="Media" width="200">
<p:graphicImage value="#{mediaController.buildUrl(post.media)}"
width="200" height="200"/>
</p:column>
<p:column headerText="Status" filterBy="#{post.moderationApproved}">
<f:facet name="filter">
<p:selectOneButton onchange="PF('ModerationPostTable').filter()">
<f:converter converterId="javax.faces.Boolean" />
<f:selectItem itemLabel="Approved" itemValue="true" />
<f:selectItem itemLabel="Rejected" itemValue="false" />
<f:selectItem itemLabel="Review" itemValue="" />
</p:selectOneButton>
</f:facet>
<h:outputText value="#{post.moderationApproved}" />
</p:column>
</p:dataTable>
</p:panel>
</ui:composition>
</html>
And the controller
#Named("moderationPostController")
#SessionScoped
#Transactional(Transactional.TxType.REQUIRED)
public class ModeratioPostController extends BaseController implements Serializable {
#Inject PostService postService;
private LazyPostDataModel posts;
// Selection
private Post selected;
#Override
protected void initSpecific() {
posts = new LazyPostDataModel(postService);
}
// Actions
public void approve() {
if (selected == null) return;
Post post = postService.find(selected.getId());
post.setModerationApproved(Boolean.TRUE);
postService.edit(post);
}
public void reject() {
if (selected == null) return;
Post post = postService.find(selected.getId());
post.setModerationApproved(Boolean.FALSE);
postService.edit(post);
}
public LazyPostDataModel getPosts() {
return posts;
}
public void setPosts(LazyPostDataModel posts) {
this.posts = posts;
}
public Post getSelected() {
return selected;
}
public void setSelected(Post selected) {
this.selected = selected;
}
}
this is because you have
filterBy="#{post.moderationApproved}"
and
<p:selectOneButton onchange="PF('ModerationPostTable').filter()">
both of these will call the filter once and cause the load method to be called twice.
Use one of them only.
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>
I have a problem that i can't solve. I have my xhtml page:
The problem is that i have a form where i insert the name and select the location of a travel. It renders an external panel "Volo" where the selectionMenu is updated with some values got from DB based on location selected. Next i want to get a value from Volo selection and update the another panel with ID="HE"(is the one called HotelEsc).
I'm in trouble with the selectionMenu in "Volo" because i can't get the value into it. Always gives an NullPointException error. Probably the problem is that i'm trying to understand how Update and render work and i am mistaking something about these operations. Hope on your help thank you.
Code of xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://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">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:panel header="DefaultPackage Form">
<h:panelGrid columns="3" id="regGrid">
<h:outputLabel for="Name">Name:</h:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<h:outputLabel for="location">Locations Available:</h:outputLabel>
<h:selectOneMenu for="location"
value="#{addDefaultPackageBean.defpackDTO.location}">
<f:ajax listener="#{addDefaultPackageBean.Search()}" render="Volo" />
<f:selectItems id="location"
value="#{addDefaultPackageBean.availableLocations}" />
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
<p:panel header="Voli Disponibili per la location selezionata"
id="Volo">
<h:outputLabel for="Fly">Volo:</h:outputLabel>
<h:selectOneMenu for="Fly" value="#{addDefaultPackageBean.fly}">
<f:selectItems id="Fly" value="#{addDefaultPackageBean.elelisfly}"
var="ElementDTO" itemValue="#{ElementDTO.name}"
itemLabel="#{ElementDTO.name}" />
</h:selectOneMenu>
<p:commandButton action="#{addDefaultPackageBean.sel()}" value="HE" render=":form,:form:regularGrid,:form:Volo" update=":form:Volo" process="form:regGrid,#this"></p:commandButton>
</p:panel>
<p:panel header="HotelEsc" id="HotelEscursioni">
<h:panelGrid columns="3" id="regularGrid">
<h:outputLabel for="Hotel">Hotel:</h:outputLabel>
<h:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</h:selectOneMenu>
<p:message for="Hotel" />
<h:outputLabel for="Escursion">Escursioni:</h:outputLabel>
<f:facet name="header">Clicca su view per vedere i dettagli</f:facet>
<p:dataTable id="Escursion" var="esc"
value="#{addDefaultPackageBean.elelisescursion}"
rowKey="#{esc.name}"
selection="#{addDefaultPackageBean.selectedEscursions}"
selectionMode="multiple">
<p:column headerText="Nome"> #{esc.name} </p:column>
<p:column headerText="Costo"> #{esc.cost} </p:column>
<p:column headerText="Data Iniziale"> #{esc.startingDate} </p:column>
<p:column headerText="Data Fine"> #{esc.endingDate} </p:column>
<f:facet name="footer">
</f:facet>
</p:dataTable>
</h:panelGrid>
</p:panel>
</h:form>
</h:body>
</html>
Code of related bean:
package beans;
import java.awt.Event;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.view.ViewScoped;
import elementManagement.ElementMgr;
import elementManagementDTO.ElementDTO;
import DefaultPackageManagement.DefaultPackageMgr;
import DefaultPackageManagementDTO.DefaultPackageDTO;
#ManagedBean(name="addDefaultPackageBean") //come viene richiamato
#ViewScoped
public class AddDefaultPackageBean{
/**
*
*/
#EJB
private DefaultPackageMgr defpackMgr;
private DefaultPackageDTO defpackDTO;
private ArrayList<ElementDTO> elelisfly;
private ArrayList<ElementDTO> elelishotel;
private ArrayList<ElementDTO> elelisescursion;
private ArrayList<ElementDTO> elelis;
private ElementDTO[] selectedEscursions;
private String fly;
private String hotel;
private boolean flag=true;
private boolean flagdopo=true;
private ArrayList<String> availableLocations;
private ElementDTO flyElem;
#EJB
private ElementMgr elemMgr;
public ElementDTO[] getSelectedEscursions() {
return selectedEscursions;
}
public void setSelectedEscursions(ElementDTO[] selectedEscursions) {
this.selectedEscursions = selectedEscursions;
}
public AddDefaultPackageBean() {
defpackDTO = new DefaultPackageDTO();
}
#PostConstruct
public void init()
{
this.elelisfly=new ArrayList<ElementDTO>();
this.elelishotel=new ArrayList<ElementDTO>();
this.elelisescursion=new ArrayList<ElementDTO>();
this.setElelis(elemMgr.getAllElements());
this.availableLocations=new ArrayList<String>();
this.flyElem=new ElementDTO();
for(ElementDTO e:elelis)
{
if (this.availableLocations.contains(e.getLocation())==false)
{
this.availableLocations.add(e.getLocation());
}
}
}
public String add() {
this.AssignElemFlyFromSelection();
this.AssignElemHotelFromSelection();
this.AssignElemEscursionFromSelection();
defpackMgr.save(defpackDTO);
return "/employee/index?faces-redirect=true";
}
public void sel()
{
System.out.print("ehila" );
this.setElelis(this.elemMgr.getAllElementsByLocation(this.defpackDTO.getLocation()));
for(ElementDTO e:elelis)
{
System.out.print("elemento della location Haiti "+e.getName());
}
this.AssignElemFlyFromSelection();
System.out.print(this.fly+"Il volo selezionato per la location è "+this.getFlyElem().getName() );
this.elelisescursion.clear();
this.elelishotel.clear();
for(ElementDTO e:elelis)
{
if(e.getType().equals("Hotel"))
{
System.out.print("ho un hotel tra gli elementi "+e.getName() );
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&((e.getEndingDate().before(this.flyElem.getEndingDate()))))
{
System.out.print("ho un hotel tra gli elementi con le date giuste"+e.getName());
this.getElelishotel().add(e);
}
}
else
{
if(e.getType().equals("Escursion"))
{
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&(e.getEndingDate().before(this.flyElem.getEndingDate())))
{
this.getElelishotel().add(e);
}
}
}
}
this.setFlag(true);
this.setFlagdopo(true);
}
public DefaultPackageDTO getDefpackDTO() {
return defpackDTO;
}
public void setDefpackDTO(DefaultPackageDTO defpackDTO) {
this.defpackDTO = defpackDTO;
}
public ArrayList<ElementDTO> getElelisfly() {
return elelisfly;
}
public void setElelisfly(ArrayList<ElementDTO> elelisfly) {
this.elelisfly = elelisfly;
}
public ArrayList<ElementDTO> getElelishotel() {
return elelishotel;
}
public void setElelishotel(ArrayList<ElementDTO> elelishotel) {
this.elelishotel = elelishotel;
}
public ArrayList<ElementDTO> getElelisescursion() {
return elelisescursion;
}
public void setElelisescursion(ArrayList<ElementDTO> elelisescursion) {
this.elelisescursion = elelisescursion;
}
public String getFly() {
return fly;
}
public void setFly(String fly) {
this.fly = fly;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
private void AssignElemFlyFromSelection()
{
for (ElementDTO elem:this.elelisfly)
{
if(elem.getName().equals(this.fly))
{
this.flyElem=elem;
}
}
}
private void AssignElemHotelFromSelection()
{
for (ElementDTO elem:this.elelishotel)
{
if(elem.getName().equals(this.hotel))
{
this.defpackDTO.getElem().add(elem);
}
}
}
private void AssignElemEscursionFromSelection()
{
for(int i=0;i<selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(selectedEscursions[i]);
}
}
public void Search(){
String s=defpackDTO.getLocation();
System.out.print("luogo scelto "+s);
this.setElelis(this.elemMgr.getAllElementsByLocation(s));
for(ElementDTO e:elelis)
{
System.out.print("aggiungo volo "+e.getName());
if(e.getType().equals("Flight"))
{
this.getElelisfly().add(e);
System.out.print("aggiungo volo "+e.getName());
}
}
this.setFlag(true);
}
public ArrayList<ElementDTO> getElelis() {
return elelis;
}
public void setElelis(ArrayList<ElementDTO> elelis) {
this.elelis = elelis;
}
public ArrayList<String> getAvailableLocations() {
return availableLocations;
}
public void setAvailableLocations(ArrayList<String> availableLocations) {
this.availableLocations = availableLocations;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public boolean isFlagdopo() {
return flagdopo;
}
public void setFlagdopo(boolean flagdopo) {
this.flagdopo = flagdopo;
}
public ElementDTO getFlyElem() {
return flyElem;
}
public void setFlyElem(ElementDTO flyElem) {
this.flyElem = flyElem;
}
}
You are somehow misunderstood the use of some attributes.
I'll post my notes on your code.
The p:commandButton inside Volo section is confusing
it doesn't have a render attribute, it's the update instead, you should remove render.
The update you have is updating the current section Volo is that what you need ?
it's processing only the first section which is regGrid, which means that the values inside Volo section won't be updated to the model inside the managedBean (causing the NullPointer), is that what you want ? don't think so.
Your "HE" button should be link this (If I understood what you want correctly)
<p:commandButton action="#{addDefaultPackageBean.sel()}"
value="HE"
update="HotelEscursioni" process="#parent">
</p:commandButton>
Hope this Helps...
After lots of attempts, i understood how render/update works. I hope the solution with the xhtml here down helps other people with the same problem:
The updates have to be done on the components that you want to refresh(for example in my situation the targets of the updates given from chosen values in selections); process has to be used to specificate which components are used to implement the action.
<!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">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:outputLabel for="Name">Name:</p:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<p:outputLabel for="Location">Locations Available:</p:outputLabel>
<p:selectOneMenu id="Location"
value="#{addDefaultPackageBean.defpackDTO.location}">
<f:selectItems
value="#{addDefaultPackageBean.availableLocations}" />
</p:selectOneMenu>
<p:commandButton action="#{addDefaultPackageBean.Search()}" value="Ciao" render=":form:Volo" update=":form:Volo :form"></p:commandButton>
<p:panel header="Voli Disponibili per la location selezionata"
id="Volo" rendered="#{addDefaultPackageBean.flag}">
<h:panelGrid columns="3" id="voloGrid">
<p:outputLabel for="Volare">Volo:</p:outputLabel>
<p:selectOneMenu for="Volare" value="#{addDefaultPackageBean.fly}">
<f:selectItems id="Volare" value="#{addDefaultPackageBean.elelisfly}"
var="Ciao" itemValue="#{Ciao.name}"
itemLabel="#{Ciao.name}" />
</p:selectOneMenu>
<p:commandButton actionListener="#{addDefaultPackageBean.sel()}" value="hesef" update=":form:voloGrid :form:HotelEscursioni" process=":form:Location,:form:voloGrid,#this"/>
</h:panelGrid>
</p:panel>
<p:panel header="HotelEscurs" id="HotelEscursioni" rendered="#{addDefaultPackageBean.flagdopo}">
<p:outputLabel for="Hotel">Hotel:</p:outputLabel>
<p:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</p:selectOneMenu>
<p:message for="Hotel" />
<p:dataTable id="Escursion" var="esc"
value="#{addDefaultPackageBean.elelisescursion}"
rowKey="#{esc.name}"
selection="#{addDefaultPackageBean.selectedEscursions}"
selectionMode="multiple">
<p:column headerText="Nome"> #{esc.name} </p:column>
<p:column headerText="Costo"> #{esc.cost} </p:column>
<p:column headerText="Data Iniziale"> #{esc.startingDate} </p:column>
<p:column headerText="Data Fine"> #{esc.endingDate} </p:column>
</p:dataTable>
</p:panel>
</h:form>
</h: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?