JSF buttons doesn't send data to bean - jsf

I have some JSF page and some bean, in cae that it is editing curent ellement i use update otherwice i use save methods.
I tryed to debug and think methods on buttons never executes
Here is my JSF page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<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"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<title>Manage panel</title>
</h:head>
<h:body>
<h3>Add/edit patient</h3>
<h:form>
<c:set var="patient" value="#{manageBean.patient}" />
<c:choose>
<c:when test="#{patient!=null}">
<p:panel id="panel1" header="Patient" style="margin-bottom:10px;">
<h:panelGrid columns="2">
<h:outputLabel for="name" value="First name" />
<p:inputText id="firstName" required="true" value="#{patient.firstName}" />
<h:outputLabel for="name" value="Family name" />
<p:inputText id="familyName" required="true" value="#{patient.familyName}" />
<h:outputLabel for="name" value="Sex" />
<p:selectOneMenu id="sex" value="#{patient.sex}">
<f:selectItems value="#{manageBean.sex}"/>
</p:selectOneMenu>
<h:outputLabel for="name" value="Birthday date" />
<p:calendar value="#{patient.birthdayDate}" mode="inline" id="birthdayDate"/>
<h:outputLabel for="name" value="Nationality" />
<p:selectOneMenu id="nationality" value="#{patient.nationality}">
<f:selectItems value="#{manageBean.nationality}"/>
</p:selectOneMenu>
<h:outputLabel for="name" value="Adress" />
<p:inputText id="adress" required="true" value="#{patient.adress}" />
<h:outputLabel for="name" value="Phone number" />
<p:inputMask id="phoneNumber" required="true" value="#{patient.phoneNumber}" mask="(999) 999-9999"/>
</h:panelGrid>
</p:panel>
<p:commandButton value="Update" type="submit" action="#{manageBean.update(patient)}" />
</c:when>
<c:otherwise>
<p:panel id="panel2" header="Patient" style="margin-bottom:10px;">
<h:panelGrid columns="2">
<h:outputLabel for="name" value="First name" />
<p:inputText id="firstName" required="true" value="" />
<h:outputLabel for="name" value="Family name" />
<p:inputText id="familyName" required="true" value="" />
<h:outputLabel for="name" value="Sex" />
<p:selectOneMenu id="sex" value="">
<f:selectItems value="#{manageBean.sex}"/>
</p:selectOneMenu>
<h:outputLabel for="name" value="Birthday date" />
<p:calendar mode="inline" id="birthdayDate"/>
<h:outputLabel for="name" value="Nationality" />
<p:selectOneMenu id="nationality" value="">
<f:selectItems value="#{manageBean.nationality}"/>
</p:selectOneMenu>
<h:outputLabel for="name" value="Adress" />
<p:inputText id="adress" required="true" value="" />
<h:outputLabel for="name" value="Phone number" />
<p:inputMask id="phoneNumber" required="true" value="" mask="(999) 999-9999"/>
</h:panelGrid>
</p:panel>
<p:commandButton value="Save" action="#{manageBean.save(firstName, familyName, sex, birthdayDate, nationality, adress, phoneNumber)}" />
</c:otherwise>
</c:choose>
</h:form>
</h:body>
</html>
Here is my bean methods:
public String update(Patient patient) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.update(patient);
tx.commit();
} catch (HibernateException ex) {
if (tx != null) {
tx.rollback();
}
ex.printStackTrace();
} finally {
session.close();
}
return "go_home";
}
public String save(String fitstName, String familyName, Sex sex, Date birthdayDate, Nationality nationallity, String adress, String phoneNumber){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Patient patient = new Patient();
patient.setFirstName(fitstName);
patient.setFamilyName(familyName);
patient.setSex(sex);
patient.setBirthdayDate(birthdayDate);
patient.setNationality(nationallity);
patient.setAdress(adress);
patient.setPhoneNumber(phoneNumber);
session.save(patient);
tx.commit();
} catch (HibernateException ex) {
if (tx != null) {
tx.rollback();
}
ex.printStackTrace();
} finally {
session.close();
}
return "go_home";
}

Once u give the value attribute in your input tags it ll directly bind the given values to the java class. Create the class variables in ur java class and bind the input tags. EX:-
In your bean class create variables like
private String firstName
and create the getter and setter methods
<f:view>
<h3>Add/edit patient</h3>
<h:form>
<p:panel id="panel1" header="Patient" style="margin-bottom:10px;">
<h:panelGrid columns="2">
<h:outputLabel for="name" value="First name" />
<p:inputText id="firstName" required="true" value="#{manageBean.firstName}" />
<h:outputLabel for="name" value="Family name" />
<p:inputText id="familyName" required="true" value="#{manageBean.familyName}" />
<h:outputLabel for="name" value="Sex" />
<p:selectOneMenu id="sex" value="#{manageBean.sex}">
<f:selectItems value="#{manageBean.sex}"/>
</p:selectOneMenu>
<h:outputLabel for="name" value="Birthday date" />
<p:calendar value="#{manageBean.birthdayDate}" mode="inline" id="birthdayDate"/>
<h:outputLabel for="name" value="Nationality" />
<p:selectOneMenu id="nationality" value="#{manageBean.nationality}">
<f:selectItems value="#{manageBean.nationality}"/>
</p:selectOneMenu>
<h:outputLabel for="name" value="Adress" />
<p:inputText id="adress" required="true" value="#{manageBean.adress}" />
<h:outputLabel for="name" value="Phone number" />
<p:inputMask id="phoneNumber" required="true" value="#{manageBean.phoneNumber}" mask="(999) 999-9999"/>
</h:panelGrid>
</p:panel>
<p:commandButton value="Update" type="submit" action="#{manageBean.update}" />
</h:form>
Create a new jsp page and copy-paste these codes inside body tag.
In your java class create the variables and getter setter methods.
Update should be a method which returns a string.

Related

Disable/Delete Not Existing Validation

I implement a <h:form> to edit Employee data which gets preloaded from the database. The preload works fine - all fields get filled with data. The <h:form id="editEmployeeForm"> is surrounded by a <h:form> which contains a <p:dataTable>.
When I do an edit on Employee data and click the "Speichern"-button nothing happens. <p:messages> says all my fields are empty what is obviously a wrong validation because all fields are prefilled. Then I deleted all <p:message> tags from my <h:inputText> tags to check whether the doSaveEmployeeEdit() gets called at all. But nothing happens - no error in console, etc. Even a simple System.out.println() doesn't get printed from the doSaveEmployeeEdit() at all.
Below the <p:dialog> what I have at the time:
<h:form id="editEmployeeForm">
<p:dialog header="Angestellten ändern" id="employeeEditDialog" widgetVar="employeeEditDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false" closeOnEscape="true">
<p:outputPanel id="employeeDataEdit" rendered="#{not empty employeeEditController.employee}">
<h:panelGrid columns="2">
<p:outputLabel for="usernameEdit" value="Benutzername: " />
<p:inputText id="usernameEdit" value="#{employeeEditController.employee.username}" disabled="true" />
</h:panelGrid>
<p:separator/>
<h:panelGrid columns="6">
<p:outputLabel for="firstnameEdit" value="Vorname: " />
<p:inputText id="firstnameEdit" value="#{employeeEditController.employee.firstName}" />
<p:outputLabel for="lastnameEdit" value="Nachname: " />
<p:inputText id="lastnameEdit" value="#{employeeEditController.employee.lastName}" />
<p:outputLabel for="birthdayEdit" value="Geburtsdatum: " />
<p:inputMask mask="99/99/9999" id="birthdayEdit" value="#{employeeEditController.employee.birthday}" />
<p:outputLabel for="locationEdit" value="Wohnort: " />
<p:inputText id="locationEdit" value="#{employeeEditController.employee.location}" />
<p:outputLabel for="streetEdit" value="Straße: " />
<p:inputText id="streetEdit" value="#{employeeEditController.employee.streetName}" />
<p:outputLabel for="postcodeEdit" value="Postleitzahl: " />
<p:inputMask id="postcodeEdit" mask="9999?9" slotChar=" " value="#{employeeEditController.employee.postcode}" />
<p:outputLabel for="phonenumberEdit" value="Telefonnummer: " />
<p:inputMask id="phonenumberEdit" mask="9?99999999999" slotChar=" " maxlength="12" value="#{employeeEditController.employee.phoneNumber}" />
<p:outputLabel for="emailEdit" value="Email: " />
<p:inputText id="emailEdit" validatorMessage="Ungültiges Email-Format!" value="#{employeeEditController.employee.email}">
<f:validateRegex pattern="^$|^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
</p:inputText>
</h:panelGrid>
<p:separator/>
<h:panelGrid columns="6">
<p:outputLabel for="familyStatus" value="Familienstatus: " />
<p:selectOneMenu id="familyStatus" value="#{employeeEditController.employee.familyStatus}" style="width:150px">
<f:selectItem itemLabel="Wähle Familienstatus" itemValue="#{employeeEditController.employee.familyStatus}" />
<f:selectItems value="#{enumController.familyStatus}" />
</p:selectOneMenu>
<p:outputLabel for="Religion" value="Religion: " />
<p:selectOneMenu id="Religion" value="#{employeeEditController.employee.religion}" style="width:150px">
<f:selectItem itemLabel="Wähle Religion" itemValue="#{employeeEditController.employee.religion}" />
<f:selectItems value="#{enumController.religions}" />
</p:selectOneMenu>
<p:outputLabel for="Role" value="Rolle: " />
<p:selectOneMenu id="Role" value="#{employeeEditController.employee.workRole}" style="width:150px">
<f:selectItem itemLabel="Wähle Arbeitsrolle" itemValue="#{employeeEditController.employee.workRole}" />
<f:selectItems value="#{enumController.workRoles}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator/>
<h:panelGrid columns="3">
<p:commandButton value="Speichern" action="#{employeeEditController.doSaveEmployeeEdit()}" />
<p:commandButton value="Neu laden" action="#{employeeEditController.doReloadEmployee()}" />
<p:commandButton value="Abbruch" onclick="PF('employeeEditDialog').hide()" />
</h:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
What can be the reason that html or whatever still do the validation and don't call the doSaveEmployeeEdit()?
UPDATE:
I made a new xhtml-file with same outputs - no validation anymore. But my controller method doesn't get called.
My children.xhtml:
<h:body>
<body class="theme-blue sidebar-mini sidebar-collapse">
<div class="wrapper">
<div class="content-wrapper" style="min-height: 1126px;">
<section class="content">
<div class="box">
<div class="box-body">
<h:form id="childForm">
<p:dataTable id="childTable" var="child" value="#{childController.children}">
<p:column headerText="Vorname">
<h:outputText value="#{child.firstName}" />
</p:column>
<p:column headerText="Nachname">
<h:outputText value="#{child.lastName}" />
</p:column>
<p:column headerText="Geburtsdatum">
<h:outputText value="#{child.birthday}" />
</p:column>
<p:column style="width:32px;text-align: center">
<p:commandButton update=":childForm:childEdit" oncomplete="PF('childEditDialog').show()" icon="ui-icon-note" title="Bearbeiten">
<f:setPropertyActionListener value="#{child}" target="#{childEditController.childEdit}" />
</p:commandButton>
</p:column>
</p:dataTable>
<p:dialog header="Kind bearbeiten" widgetVar="childEditDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:messages autoUpdate="true" />
<p:outputPanel id="childEdit" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty childEditController.childEdit}" columnClasses="label,value">
<p:outputLabel id="primParent" value="primäres Elternteil:" />
<p:inputText for="primParent" value="#{childEditController.childEdit.primaryParent.id}" disabled="true" />
<p:outputLabel id="firstName" value="Vorname:" />
<p:inputText for="firstName" value="#{childEditController.childEdit.firstName}" />
<p:outputLabel id="lastName" value="Nachname:" />
<p:inputText for="lastName" value="#{childEditController.childEdit.lastName}" />
<p:outputLabel id="birthDay" value="Geburtsdatum:" />
<p:inputText for="birthDay" value="#{childEditController.childEdit.birthday}" />
<p:outputLabel id="emgNum" value="Notfallkontakt:" />
<p:inputText for="emgNum" value="#{childEditController.childEdit.emergencyNumber}" />
<p:outputLabel id="imgName" value="Bildname:" />
<p:inputText for="imgName" value="#{childEditController.childEdit.imgName}" />
<p:outputLabel for="gender" value="Geschlecht: " />
<p:inputText id="gender" value="#{childEditController.childEdit.gender}" disabled="true" />
<p:separator />
<h:panelGrid columns="3">
<p:commandButton value="Speichern" action="#{childEditController.doSaveChild}" update=":childForm:childTable" />
<p:commandButton value="Abbruch" onclick="PF('childEditDialog').hide()" immediate="true" />
</h:panelGrid>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</div>
</div>
</section>
</div>
</div>
</body>
</h:body>
My childEditController:
#Component
#Scope("request")
public class ChildEditController {
#Autowired
private ChildService childService;
private Child childEdit;
public Child getChildEdit() {
return childEdit;
}
public void setChildEdit(Child childEdit) {
this.childEdit = childEdit;
}
public void doSaveChild(){
childEdit = childService.saveChild(childEdit);
childEdit = null;
}
}

p:commandButton inside p:dialog does not work

I have this problem and I search here and some pages on Google and none of the answers worked for me.
I have the following dialog:
<!-- Dialog Fechar Pedido -->
<p:dialog header="Fechar Pedido" widgetVar="clsPedido" id="clsPedido" minWidth="550">
<h:form prependId="true" id="frmClsPedido">
<p:panel id="pnlDialogClsPedido" header="Informe a forma de pagamento">
<h:panelGrid id="grdClsPedido" columns="2" cellpadding="5">
<p:outputLabel value="Valor Total:." />
<p:outputLabel value="R$ #{pedidoMB.totalPedido}" size="5" style="color: red;">
<f:convertNumber currencySymbol="R$" integerOnly="true" pattern="#0.00" locale="pt_BR" minFractionDigits="1" minIntegerDigits="1" />
</p:outputLabel>
<p:outputLabel value="Valor Recebido:." />
<pe:inputNumber id="vlrRecebido" value="#{pedidoMB.vlrRecebido}" minValue="0" required="true" onblur="returnValue(this.value)" requiredMessage="Informe o valor recebido!" decimalPlaces="2" decimalSeparator="," thousandSeparator="." />
<p:outputLabel value="Pagamento em:." />
<p:selectOneRadio id="frmPagamento" value="#{pedidoMB.frmPagamento}" onchange="daTroco(this.value);" required="true" requiredMessage="Informe a forma de pagamento!">
<f:selectItem itemLabel="Dinheiro" itemValue="DIN" />
<f:selectItem itemLabel="Débito" itemValue="DEB" />
<f:selectItem itemLabel="Crédito" itemValue="CRED" />
<f:selectItem itemLabel="Vale Refeição" itemValue="REF" />
</p:selectOneRadio>
<p:outputLabel value="Valor Troco:." />
<p:inputText value="#{pedidoMB.vlrTroco}" size="5" style="color: blue;" id="vlrTroco" widgetVar="vlrTroco" readonly="true">
<f:convertNumber currencySymbol="R$" integerOnly="true" pattern="#0.00" locale="pt_BR" minFractionDigits="1" minIntegerDigits="1" />
</p:inputText>
</h:panelGrid>
<h:messages></h:messages>
<div align="right">
<p:commandButton icon="ui-icon-disk" actionListener="#{pedidoMB.doFecharPedido}" />
</div>
</p:panel>
</h:form>
</p:dialog>
And I have the following method at my mbean:
public void doFecharPedido(ActionEvent event) {
if (getId() != null) {
Pedido p = getService().findById(getId());
getService().fecharPedido(getVlrRecebido(), getVlrTroco(), p);
}
}
I already tried removing the mbean ActionEvent but nothing seems to work.
Why not simply write
<p:commandButton icon="ui-icon-disk" action="#{pedidoMB.doFecharPedido}" />
and
public void doFecharPedido() {
if(getId() != null) {
Pedido p = getService().findById(getId());
getService().fecharPedido(getVlrRecebido(), getVlrTroco(), p);
}
}
?
The problem was a validation error. For some reason the inputNumber from PF extension does not accept a paste value or some other form of automatic fill of the field.

display message after page load, if a combobox is empty

I tried populating the collection in the #PostConstruct method, then a NPE is thrown.
Also tried redirecting, but I get IllegalStateException: Response already committed.
this.networks = this.getNetworks();
if (this.networks.isEmpty()) {
JsfUtils jsfUtils = new JsfUtils();
jsfUtils.displayMessage("WARN", "No network inserted!", "Insert a network!");
}
Then I tried using FacesMessage directly inside the getter method. The message isn't shown, though the method is being executed since I see the message in the console.
public List<Network> getNetworks() {
if (this.networks == null) {
networks = networkBean.findWithNamedQuery("Network.findAll");
if (networks.isEmpty()) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Insert a network!",""));
System.out.println(">>>>>>>>>>>> Insert a Network!");
}
}
return networks;
}
Using the same structure as the first in a #PostLoad method also doesn't display any message.
Page code:
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:jsf="http://xmlns.jcp.org/jsf" xmlns:p="http://primefaces.org/ui" xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
template="/WEB-INF/tpl/template1.xhtml">
<ui:define name="title">Add Stablishment</ui:define>
<ui:define name="header">Add Stablishment</ui:define>
<ui:define name="content">
<h:form id="form" enctype="multipart/form-data">
<p:growl id="growl" autoUpdate="true" showDetail="true" sticky="true" globalOnly="true" />
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="categories" value="Category:" />
<p:selectOneMenu id="categories" value="#{stablishmentMB.category.id}">
<f:selectItem itemValue="" itemLabel="-- Select --" noSelectionOption="true" />
<f:selectItems value="#{stablishmentCategoryMB.categories}" var="category" itemLabel="#{category.name}" itemValue="#{category.id}" />
</p:selectOneMenu>
<p:message for="categories" />
<p:outputLabel for="networks" value="Network:" />
<p:selectOneMenu id="networks" value="#{stablishmentMB.network.id}">
<f:selectItem itemValue="" itemLabel="-- Selecione --" noSelectionOption="true" />
<f:selectItems value="#{networkMB.networks}" var="network" itemLabel="#{network.tradeName}" itemValue="#{network.id}" />
</p:selectOneMenu>
<p:message for="networks" />
<p:outputLabel for="cnpj" value="CNPJ:" />
<p:inputMask id="cnpj" pt:placeholder="99.999.999/9999-99" mask="99.999.999/9999-99" value="#{stablishmentMB.stablishment.cnpj}" required="true" />
<p:message for="cnpj" />
<p:outputLabel for="companyName" value="Company Name:" />
<p:inputText id="companyName" value="#{stablishmentMB.stablishment.companyName}" required="true" />
<p:message for="companyName" />
<p:outputLabel for="tradeName" value="Trade Name:" />
<p:inputText id="tradeName" value="#{stablishmentMB.stablishment.tradeName}" required="true" />
<p:message for="tradeName" />
<p:outputLabel for="zipCode" value="Zip Code:" />
<p:inputMask id="zipCode" mask="99999-999" value="#{stablishmentMB.zipCode.number}" required="true">
<p:ajax event="blur" listener="#{stablishmentMB.findByZipCode}" update="street neighbourhood city state" />
</p:inputMask>
<p:message for="zipCode" />
<p:outputLabel for="state" value="State:" />
<p:inputText id="state" value="#{stablishmentMB.state.abbreviation}" required="true" />
<p:message for="state" />
<p:outputLabel for="city" value="City:" />
<p:inputText id="city" value="#{stablishmentMB.city.nome}" required="true" />
<p:message for="city" />
<p:outputLabel for="neighbourhood" value="Neighbourhood:" />
<p:inputText id="neighbourhood" value="#{stablishmentMB.neighbourhood.nome}" />
<p:message for="neighbourhood" />
<p:outputLabel for="street" value="Street:" />
<p:inputText id="street" value="#{stablishmentMB.street.name}" required="true" />
<p:message for="street" />
<p:outputLabel for="number" value="Nº:" />
<p:inputText id="number" value="#{stablishmentMB.stablishment.number}" required="true" />
<p:message for="number" />
<p:outputLabel for="complement" value="Complement:" />
<p:inputText id="complement" value="#{stablishmentMB.stablishment.complement}" />
<p:message for="complement" />
<p:outputLabel for="telephone" value="Telephone:" />
<p:inputMask mask="(99) 9999-9999" id="telephone" value="#{stablishmentMB.stablishment.telephone}" />
<p:message for="telephone" />
<p:outputLabel for="contact" value="Contact:" />
<p:inputText id="contact" value="#{stablishmentMB.stablishment.contact}" />
<p:message for="contact" />
<p:outputLabel for="email" value="E-mail:" />
<p:inputText id="email" value="#{stablishmentMB.stablishment.email}" />
<p:message for="email" />
<p:outputLabel for="site" value="Site:" />
<p:inputText id="site" value="#{stablishmentMB.stablishment.site}" />
<p:message for="site" />
<p:outputLabel for="latitude" value="Latitude:" />
<p:inputText id="latitude" value="#{stablishmentMB.stablishment.latitude}" />
<p:message for="latitude" />
<p:outputLabel for="longitude" value="Longitude:" />
<p:inputText id="longitude" value="#{stablishmentMB.stablishment.longitude}" />
<p:message for="longitude" />
<p:commandButton action="#{stablishmentMB.save}" value="Save" update="#form" />
</h:panelGrid>
</h:form>
</ui:define>
You should remove your code from the getter because a getter is not mean to do such staff and always #PostConstruct will be executed before any getter on your bean!
A quick fix to your problem is to move <p:growl> to the end of page this will make your bean construction happens before the renderer try to render <p:growl>.

jsf - Dropdown not updating its selected value with the entity's - NPE in selected entity's getId()

In the JSF page for updating some entity, a dropdown is used to select the desired row:
Then all fields are filled with the selected row information, except the dropdowns:
I created two methods, one for loading each dropdown, in the entity's managed bean. For the first one I used the following code:
public List<Rede> getRedes() {
if (this.redes == null) {
redes = redeBean.findWithNamedQuery("Rede.findAll");
}
if (this.estabelecimento.getId() > 0) {
Map<String, Object> map = new HashMap<>();
map.put("estabelecimento_id", this.estabelecimento.getId());
this.rede = (Rede) redeBean.findWithNamedQuery("Rede.findByEstabelecimentoId", map).get(0);
for (Rede r : redes) {
if(Objects.equals(this.rede.getId(), r.getId())) {
this.rede = r;
}
}
}
return redes;
}
But estabelecimento.getId() throws NullPointerException, but estabelecimento is not null. Estabelecimento is instantiated in the PostConstruct method.
The alterar.xhtml page:
<ui:define name="content">
<f:metadata>
<f:viewParam name="id" value="#{estabelecimentoMB.estabelecimento.id}" />
<f:viewParam name="redeId" value="#{estabelecimentoMB.rede.id}" />
<f:viewParam name="categoriaId" value="#{estabelecimentoMB.categoria.id}" />
</f:metadata>
<h:form id="form" enctype="multipart/form-data">
<p:growl id="growl" showDetail="true" sticky="true" globalOnly="true" />
<p:panelGrid id="pnl" columns="2">
<p:outputLabel for="estabelecimentos" value="Estabelecimento:" />
<p:selectOneMenu id="estabelecimentos" value="#{estabelecimentoMB.estabelecimento.id}" >
<f:selectItem itemValue="0" itemLabel="-- Selecione --" />
<f:selectItems value="#{estabelecimentoMB.estabelecimentos}" var="x" itemValue="#{x.id}" itemLabel="#{x.nomefantasia}" />
<p:ajax event="change" listener="#{estabelecimentoMB.prepareEdit(estabelecimentoMB.estabelecimento.id)}" update="#form" />
</p:selectOneMenu>
<p:message for="estabelecimentos" />
</p:panelGrid>
<p:separator />
<p:panelGrid id="pnl-info" columns="3">
<p:outputLabel for="cnpj" value="CNPJ:" />
<p:inputText id="cnpj" required="true" value="#{estabelecimentoMB.estabelecimento.cnpj}" />
<p:message for="cnpj" />
<p:outputLabel for="razaosocial" value="Razão Social:" />
<p:inputText id="razaosocial" required="true" value="#{estabelecimentoMB.estabelecimento.razaosocial}" />
<p:message for="razaosocial" />
<p:outputLabel for="nomefantasia" value="Nome Fantasia:" />
<p:inputText id="nomefantasia" required="true" value="#{estabelecimentoMB.estabelecimento.nomefantasia}" />
<p:message for="nomefantasia" />
<p:outputLabel for="cep" value="CEP:" />
<p:inputText id="cep" required="true" value="#{estabelecimentoMB.estabelecimento.cep}" />
<p:message for="cep" />
<p:outputLabel for="logradouro" value="Logradouro:" />
<p:inputText id="logradouro" required="true" value="#{estabelecimentoMB.estabelecimento.logradouro}" />
<p:message for="logradouro" />
<p:outputLabel for="numero" value="Número:" />
<p:inputText id="numero" required="true" value="#{estabelecimentoMB.estabelecimento.numero}" />
<p:message for="numero" />
<p:outputLabel for="razaosocial" value="Razão Social:" />
<p:inputText id="complemento" required="true" value="#{estabelecimentoMB.estabelecimento.razaosocial}" />
<p:message for="razaosocial" />
<p:outputLabel for="bairro" value="Bairro:" />
<p:inputText id="bairro" required="true" value="#{estabelecimentoMB.estabelecimento.bairro}" />
<p:message for="bairro" />
<p:outputLabel for="cidade" value="Cidade:" />
<p:inputText id="cidade" required="true" value="#{estabelecimentoMB.estabelecimento.cidade}" />
<p:message for="cidade" />
<p:outputLabel for="estado" value="Estado:" />
<p:inputText id="estado" required="true" value="#{estabelecimentoMB.estabelecimento.estado}" />
<p:message for="estado" />
<p:outputLabel for="pais" value="País:" />
<p:inputText id="pais" required="true" value="#{estabelecimentoMB.estabelecimento.pais}" />
<p:message for="pais" />
<p:outputLabel for="telefone" value="Telefone:" />
<p:inputText id="telefone" required="true" value="#{estabelecimentoMB.estabelecimento.telefone}" />
<p:message for="telefone" />
<p:outputLabel for="contato" value="Contato:" />
<p:inputText id="contato" required="true" value="#{estabelecimentoMB.estabelecimento.contato}" />
<p:message for="contato" />
<p:outputLabel for="email" value="E-mail:" />
<p:inputText id="email" required="true" value="#{estabelecimentoMB.estabelecimento.email}" />
<p:message for="email" />
<p:outputLabel for="site" value="Site:" />
<p:inputText id="site" required="true" value="#{estabelecimentoMB.estabelecimento.site}" />
<p:message for="site" />
<p:outputLabel for="latitude" value="Latitude:" />
<p:inputText id="latitude" value="#{estabelecimentoMB.estabelecimento.latitude}" />
<p:message for="latitude" />
<p:outputLabel for="longitude" value="Longitude:" />
<p:inputText id="longitude" value="#{estabelecimentoMB.estabelecimento.longitude}" />
<p:message for="longitude" />
<p:outputLabel for="redes" value="Rede:" />
<p:selectOneMenu id="redes" value="#{estabelecimentoMB.rede.id}" >
<f:selectItem itemLabel="-- Selecione --" itemValue="0" />
<f:selectItems itemLabel="#{rede.nomefantasia}" itemValue="#{rede.id}" value="#{redeMB.redes}" var="rede" />
</p:selectOneMenu>
<p:message for="redes" />
<p:outputLabel for="categorias" value="Categoria:" />
<p:selectOneMenu id="categorias" value="#{estabelecimentoMB.categoria.id}" >
<f:selectItem itemLabel="-- Selecione --" itemValue="0" />
<f:selectItems itemLabel="#{categoria.nome}" itemValue="#{categoria.id}" value="#{categoriaEstabelecimentoMB.categorias}" var="categoria" />
</p:selectOneMenu>
<p:message for="categorias" />
<p:commandButton action="#{estabelecimentoMB.save}" value="Salvar" update="#form" />
</p:panelGrid>
</h:form>
</ui:define>
The prepareEdit method has only this line: this.estabelecimento = this.estabelecimentoBean.findById(id);
EstabelecimentoMB is ViewScoped.
Added noSelectionOption="true" to both dropdowns;
Changed the prepareEdit method to:
public void prepareEdit(int id) {
Map<String, Object> map = new HashMap<>();
map.put("estabelecimento_id", id);
this.estabelecimento = this.estabelecimentoBean.findById(id);
this.rede = (Rede) this.redeBean.findWithNamedQuery("Rede.findByEstabelecimentoId", map).get(0);
this.categoria = (CategoriaEstabelecimento) this.categoriaBean.findWithNamedQuery("CategoriaEstabelecimento.findByEstabelecimentoId", map).get(0);
}
It's working now.

RequestScope bean and Prime Faces Collector

I got a problem. I have a bean CreateProjectBean which is RequestScope bean. I want to use Prime Faces component called Collector so i can dynamicly change in view createProject table groupRoleAdapters which is a field of CreateProjectBean. Unforuntely every time i click "add" or "remove" in collector, there is a new request being sent to bean, which means, that GroupRoleAdapters is being created once more - of course empty.
My collector code:
<p:panel header="Add group">
<h:panelGrid columns="2">
<h:outputLabel value="Group name: *" for="txt_title"></h:outputLabel>
<h:selectOneMenu id="groupMenu"
value="#{createProjectBean.groupRoleAdapter.groupName}">
<f:selectItems value="#{createProjectBean.groupNames}"
var="group" itemValue="#{group}" itemLabel="#{group}" />
</h:selectOneMenu>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:groupMenu" />
<h:outputLabel value="Role name: *" for="txt_title"></h:outputLabel>
<h:selectOneMenu id="roleMenu"
value="#{createProjectBean.groupRoleAdapter.roleName}">
<f:selectItems value="#{createProjectBean.roleNames}" var="role"
itemValue="#{role}" itemLabel="#{role}" />
</h:selectOneMenu>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:roleMenu" />
<f:verbatim>
<br />
</f:verbatim>
<p:commandButton value="Add" update="creationForm:out"
action="#{createProjectBean.reinit}">
<p:collector value="#{createProjectBean.groupRoleAdapter}"
addTo="#{createProjectBean.selectedGroupRoleAdapters}"/>
</p:commandButton>
</h:panelGrid>
</p:panel>
<f:verbatim>
<br />
</f:verbatim>
<p:outputPanel id="out">
<p:dataTable value="#{createProjectBean.selectedGroupRoleAdapters}"
var="groupRoleAdapter">
<p:column>
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{groupRoleAdapter.groupName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Role" />
</f:facet>
<h:outputText value="#{groupRoleAdapter.roleName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Operation" />
</f:facet>
<p:commandLink value="Remove" update="creationForm:out">
<p:collector value="#{groupRoleAdapter}" removeFrom="#{createProjectBean.selectedGroupRoleAdapters}" />
</p:commandLink>
</p:column>
</p:dataTable>
</p:outputPanel>
I'd like to use the same instance of bean while adding and removing groupRoleAdapters from list selectedGroupRoleAdapters (represented by collector table), but create new instance of bean every time i try to create new project, so changing scope to sessionScope is not what i can accept.
Thanks in advance for every help.
I attach full code of that view:
<!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.prime.com.tr/ui">
<ui:composition template="/templates/template.xhtml">
<ui:define name="head">
<title>Create Project</title>
<link rel="stylesheet" type="text/css"
href="#{facesContext.externalContext.requestContextPath}/styles/style.css" />
</ui:define>
<ui:define name="content">
<div class="mainTable">
<center><f:view>
<h:outputText id="error" rendered="false" />
<h:message styleClass="errorMessage" for="error" />
<h:form id="creationForm">
<h:panelGrid columns="2" width="420">
<h:panelGroup width="300">
<h:outputLabel styleClass="formLabel" value="Name: "></h:outputLabel>
</h:panelGroup>
<h:panelGroup>
<h:inputText styleClass="formField" id="name"
value="#{createProjectBean.project.name}" required="true">
<f:validateLength minimum="3" />
</h:inputText>
</h:panelGroup>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:name" />
<h:panelGroup>
<h:outputLabel styleClass="formLabel" value="Short Name: " />
</h:panelGroup>
<h:panelGroup>
<h:inputText styleClass="formField" id="shortname"
value="#{createProjectBean.project.shortname}" required="false">
<f:validateLength maximum="8" />
</h:inputText>
</h:panelGroup>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:shortname" />
<h:panelGroup>
<h:outputLabel styleClass="formLabel" value="Homepage: " />
</h:panelGroup>
<h:panelGroup>
<h:inputText styleClass="formField" id="homepage"
value="#{createProjectBean.project.homepage}" required="false">
</h:inputText>
</h:panelGroup>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:hostname" />
<h:panelGroup>
<h:outputLabel styleClass="formLabel" value="Description: " />
</h:panelGroup>
<h:panelGroup>
<h:inputTextarea styleClass="formField" id="description"
value="#{createProjectBean.project.description}" required="false"
cols="50" rows="10" />
</h:panelGroup>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:description" />
<h:panelGroup>
<h:outputLabel styleClass="formLabel" value="Plugins: " />
</h:panelGroup>
<h:selectManyListbox id="pluginBox"
value="#{createProjectBean.selectedPluginNames}">
<f:selectItems value="#{createProjectBean.pluginNames}"
var="plugin" itemValue="#{plugin}" itemLabel="#{plugin}" />
</h:selectManyListbox>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:pluginBox" />
<h:panelGroup>
<h:outputLabel styleClass="formLabel" value="Tags: " />
</h:panelGroup>
<h:selectManyListbox id="tagBox"
value="#{createProjectBean.project.tags}">
<f:selectItems value="#{createProjectBean.allTags}" var="tag"
itemValue="#{tag}" itemLabel="#{tag.name}" />
</h:selectManyListbox>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:tagBox" />
<f:verbatim>
<br />
</f:verbatim>
<p:panel header="Add group">
<h:panelGrid columns="2">
<h:outputLabel value="Group name: *" for="txt_title"></h:outputLabel>
<h:selectOneMenu id="groupMenu"
value="#{createProjectBean.groupRoleAdapter.groupName}">
<f:selectItems value="#{createProjectBean.groupNames}"
var="group" itemValue="#{group}" itemLabel="#{group}" />
</h:selectOneMenu>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:groupMenu" />
<h:outputLabel value="Role name: *" for="txt_title"></h:outputLabel>
<h:selectOneMenu id="roleMenu"
value="#{createProjectBean.groupRoleAdapter.roleName}">
<f:selectItems value="#{createProjectBean.roleNames}" var="role"
itemValue="#{role}" itemLabel="#{role}" />
</h:selectOneMenu>
<f:verbatim>
<br />
</f:verbatim>
<h:message styleClass="errorMessage" for="creationForm:roleMenu" />
<f:verbatim>
<br />
</f:verbatim>
<p:commandButton value="Add" update="creationForm:out"
action="#{createProjectBean.reinit}">
<p:collector value="#{createProjectBean.groupRoleAdapter}"
addTo="#{createProjectBean.selectedGroupRoleAdapters}"/>
</p:commandButton>
</h:panelGrid>
</p:panel>
<f:verbatim>
<br />
</f:verbatim>
<p:outputPanel id="out">
<p:dataTable value="#{createProjectBean.selectedGroupRoleAdapters}"
var="groupRoleAdapter">
<p:column>
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{groupRoleAdapter.groupName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Role" />
</f:facet>
<h:outputText value="#{groupRoleAdapter.roleName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Operation" />
</f:facet>
<p:commandLink value="Remove" update="creationForm:out">
<p:collector value="#{groupRoleAdapter}"
removeFrom="#{createProjectBean.selectedGroupRoleAdapters}" />
</p:commandLink>
</p:column>
</p:dataTable>
</p:outputPanel>
<f:verbatim>
<br />
</f:verbatim>
<h:commandButton value="Create" styleClass="formButton"
action="#{createProjectBean.create}" />
</h:panelGrid>
</h:form>
</f:view></center>
</div>
</ui:define>
</ui:composition>
</html>
If you're already on JSF 2.0, just put the bean in view scope, by either #ViewScoped annotation or by <managed-bean-scope>view</managed-bean-scope> in faces-config.xml.
If you're still on JSF 1.x (which I'm afraid of since you're using those ugly JSF 1.0/1.1-mandatory <f:verbatim> tags), then you have to either put bean in session scope, eventually in combination with an unique request scoped parameter which is retained in subsequent requests by h:inputHidden or f:param, or to grab a 3rd party library with a component which is able to save the state of an entire request scoped bean for the subsequent request, like Tomahawk's t:saveState.

Resources