Primefaces duplicating elements in the DOM - jsf

Every time i click on a button or enter a dialog my overlayPanel is duplicated in the DOM, making it impossible, for example, to send a simple field to the backend. I spent a lot of time trying to see if it was something related to the p:commandbutton process/update, or even if it was some wrong lifetime tied to the controller, or even watching the discussions about here.
This is a part of my VIEW with my three overlayPanel below
<ui:define name="formActionAppend">
<p:commandButton
value="#{nfesBundle.btnTransmitNFe}"
styleClass="GreenButton RaisedButton"
icon="fa fa-send"
rendered="#{nfesController.btnTransmitEnabled}"
action="#{nfesController.doNFeTransmission()}"
update="formDialog"
process="#this formDialog"
onsuccess="crudController.markAsChanged()" />
<p:commandButton
id="btnCancelNFe"
styleClass="RedButton"
value="#{nfesBundle.btnCancelNFe}"
icon="fa fa-ban"
type="button"
rendered="#{nfesCancellationController.btnCancelEnabled}"
update="#(.onCancelRequest)"
process="#this" />
<p:overlayPanel
for="btnCancelNFe"
at="left top"
my="left bottom"
appendToBody="true">
<p:panel
header="#{nfesBundle.cancellationPanelTitle}"
rendered="#{nfesCancellationController.btnCancelEnabled}"
styleClass="onCancelRequest">
<sm:row>
<sm:cell
container="100"
responsive="100"
styleClass="floatLabel">
<p:outputLabel
for="justification"
value="#{nfesBundle.cancelationInputJustification}" />
<p:inputTextarea
id="justification"
maxlength="255"
required="true"
value="#{nfesCancellationController.justification}" />
</sm:cell>
</sm:row>
<div class="clearfix" />
<f:facet name="footer">
<p:commandButton
id="btnDoNFeCancellation"
action="#{nfesCancellationController.doCancellation()}"
process="#parent"
update="formDialog"
value="#{nfesBundle.btnDoNFeCancellation}"
icon="fa fa-check"
onsuccess="crudController.markAsChanged()" />
</f:facet>
</p:panel>
</p:overlayPanel>
<p:commandButton
id="btnGenerateCCe"
value="#{nfesBundle.btnGenerateCCe}"
styleClass="OrangeButton"
icon="fa fa-pencil-square-o"
type="button"
rendered="#{nfesCCeController.btnGenerateCCeEnabled}"
update="#(.onCCeRequest)"
process="#this" />
<p:overlayPanel
for="btnGenerateCCe"
at="left top"
my="left bottom"
appendToBody="true">
<p:panel
header="#{nfesBundle.ccePanelTitle}"
rendered="#{nfesCCeController.btnGenerateCCeEnabled}"
styleClass="onCCeRequest">
<sm:row>
<sm:cell
container="100"
responsive="100"
styleClass="floatLabel">
<p:outputLabel
for="correction"
value="#{nfesBundle.cceInputCorrection}" />
<p:inputTextarea
id="correction"
maxlength="1000"
required="true"
value="#{nfesCCeController.correction}" />
</sm:cell>
</sm:row>
<div class="clearfix" />
<f:facet name="footer">
<p:commandButton
id="btnDoGenerateCCe"
action="#{nfesCCeController.doGenerateCCe()}"
process="#parent"
update="formDialog"
value="#{nfesBundle.btnDoGenerateCCe}"
icon="fa fa-check"
onsuccess="crudController.markAsChanged()" />
</f:facet>
</p:panel>
</p:overlayPanel>
<p:button
target="_blank"
styleClass="BlueTextButton RaisedButton"
value="#{nfesBundle.btnDownloadDanfePDF}"
href="#{nfesController.getLinkDownloadDanfePDF()}"
rendered="#{nfesController.btnDownloadDanfeEnabled}"
icon="fa fa-file-pdf-o" />
<p:button
target="_blank"
styleClass="BlueTextButton RaisedButton"
value="#{nfesBundle.btnDownloadNFeXML}"
href="#{nfesController.getLinkDownloadNFeXML()}"
rendered="#{nfesController.btnDownloadNFeEnabled}"
icon="fa fa-download" />
<p:commandButton
id="btnEmailNFe"
value="#{nfesBundle.btnEmailNFe}"
styleClass="RaisedButton GreenButton"
icon="fa fa-envelope-o"
type="button"
rendered="#{nfesEmailController.entity.authorized}"
update="#(.onEmailRequest)"
process="#this" />
<p:overlayPanel
for="btnEmailNFe"
at="left top"
my="left bottom"
appendToBody="true">
<p:panel
header="#{nfesBundle.emailPanelTitle}"
rendered="#{nfesEmailController.entity.authorized}"
style="width:500px;"
styleClass="onEmailRequest">
<sm:row>
<sm:cell
container="100"
responsive="100"
styleClass="floatLabel">
<p:outputLabel
for="email"
value="#{nfesBundle.emailAddress}" />
<p:inputTextarea
id="email"
required="true"
value="#{nfesEmailController.email}" />
</sm:cell>
</sm:row>
<div class="clearfix" />
<f:facet name="footer">
<p:commandButton
id="btnEmailSend"
styleClass="GreenButton RaisedButton"
action="#{nfesEmailController.sendMail()}"
process="#parent"
update="formDialog"
value="#{nfesBundle.btnEmailSend}"
icon="fa fa-check" />
</f:facet>
</p:panel>
</p:overlayPanel>
<p:button
value="#{nfesBundle.btnSaleView}"
styleClass="RaisedButton BlueTextButton"
rendered="#{nfesController.NFCeFromSale.present or nfesController.NFeFromSale.present}"
icon="fa fa-share"
outcome="sale">
<f:param
name="saleId"
value="#{nfesController.entity.sale.id}" />
</p:button>
<p:button
value="#{nfesBundle.btnStockPurchaseView}"
styleClass="RaisedButton BlueTextButton"
rendered="#{nfesController.NFeFromStockPurchase.present}"
icon="fa fa-share"
outcome="stockPurchase">
<f:param
name="stockPurchaseId"
value="#{nfesController.entity.stockPurchase.id}" />
</p:button>
<p:button
value="#{nfesBundle.btnStockTransferView}"
styleClass="RaisedButton BlueTextButton"
rendered="#{nfesController.NFeFromStockTransfer.present}"
icon="fa fa-share"
outcome="stockTransfer">
<f:param
name="stockTransferId"
value="#{nfesController.entity.stockTransfer.id}" />
</p:button>
<p:button
value="#{nfesBundle.btnVaccineApplicationsView}"
styleClass="RaisedButton BlueTextButton"
rendered="#{nfesController.NFCeFromVaccineApplication.present or nfesController.NFeFromVaccineApplication.present}"
icon="fa fa-share"
outcome="vaccineApplication">
<f:param
name="vaccineApplicationId"
value="#{nfesController.entity.vaccineApplication.id}" />
</p:button>
<p:button
value="#{nfesBundle.btnDevolutionView}"
styleClass="RaisedButton BlueTextButton"
rendered="#{nfesController.NFeFromDevolution.present}"
icon="fa fa-share"
outcome="devolution">
<f:param
name="devolutionId"
value="#{nfesController.entity.devolution.id}" />
</p:button>
</ui:define>
This is one of the three controllers of the overlayPanels
package eprecise.sgv.server.fiscal.nfes;
import java.io.IOException;
import java.io.Serializable;
import java.util.Optional;
import javax.ejb.ConcurrentAccessTimeoutException;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.net.ssl.SSLHandshakeException;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import eprecise.sgv.server.core.infra.CacheOnRenderResponse;
import eprecise.sgv.server.core.util.FacesMessageUtil;
import eprecise.sgv.server.core.validation.HandleConstraintViolations;
import eprecise.sgv.server.fiscal.nfes.events.NFeCancelSyncUnauthorized;
import eprecise.sgv.server.fiscal.nfes.events.NFeCancellationEvent;
import eprecise.sgv.server.fiscal.nfes.transmission.NFeTransmissionChannel;
#Named
#RequestScoped
#HandleConstraintViolations
#CacheOnRenderResponse
public class NfesCancellationController implements Serializable {
private static final long serialVersionUID = 1L;
private #NotNull #Size(min = 15, max = 255) String justification;
private final NfesController controller;
private final NFeTransmissionChannel transmissionChannel;
private final NFesRepository repository;
public NfesCancellationController() {
this.controller = null;
this.transmissionChannel = null;
this.repository = null;
}
#Inject
public NfesCancellationController(final NfesController controller, final NFeTransmissionChannel transmissionChannel, final NFesRepository repository) {
this.controller = controller;
this.transmissionChannel = transmissionChannel;
this.repository = repository;
}
public String getJustification() {
return this.justification;
}
public void setJustification(final String justification) {
this.justification = justification;
}
public void doCancellation() {
this.controller.setEntity(this.repository.find(this.controller.getEntity()));
if (this.isBtnCancelEnabled()) {
try {
this.controller.getEntity().cancel(this.transmissionChannel, this.justification);
this.controller.getEntity().getLastEvent().ifPresent(e -> {
if (e instanceof NFeCancellationEvent) {
FacesMessageUtil.addInfoMessage("Cancelada com sucesso");
} else if (e instanceof NFeCancelSyncUnauthorized) {
final NFeCancelSyncUnauthorized unauthorized = (NFeCancelSyncUnauthorized) e;
FacesMessageUtil.addWarnMessage(String.format("Não cancelada por: %s", unauthorized.getDetails()));
} else {
FacesMessageUtil.addInfoMessage("Transmissão efetuada, veja mais detalhes no histórico");
}
});
this.repository.update(this.controller.getEntity());
} catch (final ConcurrentAccessTimeoutException e) {
FacesMessageUtil.addWarnMessage("Não foi possível transmitir, tente novamente em alguns instantes");
} catch (final RuntimeException e) {
if ((e.getCause() instanceof SSLHandshakeException) || (e.getCause() instanceof IOException)) {
FacesMessageUtil.addWarnMessage("Houve um erro de comunicação com a sefaz. Tente novamente em alguns instantes");
} else {
throw e;
}
}
} else {
FacesMessageUtil.addErrorMessage("Não é possível cancelar a NFe");
}
}
public boolean isBtnCancelEnabled() {
return this.controller.isInViewMode() && Optional.ofNullable(this.controller.getEntity()).map(BaseNFe::isAllowedToCancel).orElse(false);
}
}
Note: I tried to use dynamic = true in the overlayPanel, and the error is gone, however my css broke entirely.
Note²: I've been doing other tests and discovering that on some machines this code works, on others it doesn't. I tried to switch browsers and make the same requests, but nothing. I really don't know what else to do
I'm using Java 8 with Primefaces 7
My OverlayPanel here
My OverlayPanel with css broke
My help video about this problem

I don't see that I use it inside a form, please put the elements inside a form.
The 'h' letter is because it is a jsf element.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
...
<h:form id="idForm">
...
</h:form>
Also note this:
Version changes 6.2 -> 7.0
OverlayPanel: appendToBody has been removed. Use appendTo="#(body)"
instead.
You can check more information here

Related

PropertyActionListener won't envoke target [duplicate]

This question already has answers here:
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
(12 answers)
How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?
(2 answers)
How to show details of current row from p:dataTable in a p:dialog and update after save
(1 answer)
Closed 8 months ago.
I try to create a page on which I can edit delete and create users.
I can't get the website to function correctly.
Apparently, I run into the problem that my user doesn't get set by the PropertyActionListener.
If I delete the createUserDialog it all functions perfectly. I don't get what I am missing.
Why is the second dialog interfering with the first.
Anyone an idea what is going on ?
Any help is much appreciated.
XHTML FILE:
<?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">
<ui:composition xmlns="http://www.w3c.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:ng="http://xmlns.jcp.org/jsf/passthrough"
xmlns:p="http://primefaces.org/ui" xmlns:o="http://omnifaces.org/ui"
template="/WEB-INF/templates/main2.xhtml">
<ui:define name="content">
<div class="wrapper" style="display:flex; flex-flow: row; height: 100%; justify-content: center; align-items: center;">
<p:card style="width: 80%; margin-bottom: 2em; box-shadow: 5px 10px 25px rgba(0, 0, 0, 0.45); border-radius: 10px 10px 10px 10px;">
<h:form id="userForm">
<p:dataTable id="usersTable" var="user" value="#{userListController.users}">
<p:column headerText="Username">
<h:outputText value="#{user.username}"/>
</p:column>
<p:column headerText="First Name">
<h:outputText value="#{user.firstName}"/>
</p:column>
<p:column headerText="Last Name">
<h:outputText value="#{user.lastName}"/>
</p:column>
<p:column headerText="Roles">
<h:outputText value="#{user.roles}" />
</p:column>
<p:column headerText="Enabled">
<h:selectBooleanCheckbox value="#{user.enabled}" disabled="true"/>
</p:column>
<p:column style="width:100px;text-align: center">
<p:commandButton update=":userForm:userEditDialog" oncomplete="PF('userEditDialog').show()" icon="pi pi-user-edit" title="Edit">
<f:setPropertyActionListener target="#{userDetailController.user()}" value="#{user}"/>
</p:commandButton>
<p:commandButton action="#{userDetailController.doDeleteUser}" icon="pi pi-trash" title="Delete" update=":userForm:usersTable">
<f:setPropertyActionListener value="#{user}" target="#{userDetailController.user()}" />
<p:confirm header="Confirmation" message="Are you sure that you want to delete this user? You cannot undo this operation." icon="ui-icon-alert" />
</p:commandButton>
</p:column>
</p:dataTable>
<p:dialog header="Edit User" id="userEditDialog" widgetVar="userEditDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="userData" rendered="#{not empty userDetailController.user}">
<h:panelGrid columns="2">
<p:outputLabel for="username" value="Username: " />
<p:inputText id="username" value="#{userDetailController.user.username}" disabled="true"/>
<p:outputLabel for="password" value="Password: " />
<p:password id="password" value="#{userDetailController.user.password}" disabled="true"/>
</h:panelGrid>
<p:separator />
<h:panelGrid columns="2">
<p:outputLabel for="firstName" value="First Name: " />
<p:inputText id="firstName" value="#{userDetailController.user.firstName}"/>
<p:outputLabel for="firstName" value="Last Name: " />
<p:inputText id="lastName" value="#{userDetailController.user.lastName}"/>
<p:outputLabel for="email" value="E-Mail: " />
<p:inputText id="email" value="#{userDetailController.user.email}"/>
<p:outputLabel for="phone" value="Phone: " />
<p:inputMask id="phone" value="#{userDetailController.user.phone}" mask="+99? 999 9999999"/>
</h:panelGrid>
<p:separator />
<p:separator />
<h:panelGrid columns="2">
<p:outputLabel for="enabled" value="Enabled: " />
<p:selectBooleanCheckbox id="enabled" value="#{userDetailController.user.enabled}"/>
</h:panelGrid>
<p:separator />
<h:panelGrid columns="3">
<p:commandButton value="Save" action="#{userDetailController.doSaveUser}" oncomplete="PF('userEditDialog').hide()" update=":userForm:usersTable"/>
<p:commandButton value="Reload" action="#{userDetailController.doReloadUser}" update=":userForm:userData"/>
<p:commandButton value="Abort" onclick="PF('userEditDialog').hide()"/>
</h:panelGrid>
</p:outputPanel>
</p:dialog>
<p:confirmDialog global="true" showEffect="fade" hideEffect="fade" width="300">
<p:commandButton value="Yes" type="button" styleClass="ui-confirmdialog-yes" icon="pi pi-check" />
<p:commandButton value="No" type="button" styleClass="ui-confirmdialog-no" icon="pi pi-times" />
</p:confirmDialog>
<p:commandButton update=":userForm:userCreateDialog" oncomplete="PF('userCreateDialog').show()" icon="pi pi-user-edit" title="Create">
</p:commandButton>
<p:dialog header="Create New User" id="userCreateDialog" widgetVar="userCreateDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="newUserData">
<h:panelGrid columns="2">
<p:outputLabel for="newUsername" value="Username: " />
<p:inputText id="newUsername" value="#{userDetailController.newUser.username}" required="true"/>
<p:outputLabel for="newPassword" value="Password: " />
<p:password id="newPassword" value="#{userDetailController.newUser.password}" required="true"/>
</h:panelGrid>
<p:separator />
<h:panelGrid columns="2">
<p:outputLabel for="newFirstName" value="First Name: " />
<p:inputText id="newFirstName" value="#{userDetailController.newUser.firstName}"/>
<p:outputLabel for="newLastName" value="Last Name: " />
<p:inputText id="newLastName" value="#{userDetailController.newUser.lastName}"/>
<p:outputLabel for="NewEmail" value="Email: "/>
<p:inputText id="NewEmail" value="#{userDetailController.newUser.email}"/>
<p:outputLabel for="newPhone" value="Phone: " />
<p:inputMask id="newPhone" value="#{userDetailController.newUser.phone}" mask="+99? 999 9999999"/>
</h:panelGrid>
<p:separator />
<div class="wrapper1" style="margin-bottom: 30px;">
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel for="d" value="Working Room:"/>
<p:selectOneMenu id="d" value="#{userDetailController.newUser.workingRoom}" style="width:200px">
<f:selectItems value="#{userDetailController.allRooms}" var="aRoom" itemLabel="#{aRoom.roomName}" itemValue="#{aRoom}" />
</p:selectOneMenu>
</h:panelGrid>
</div>
<p:separator />
<h:panelGrid columns="3">
<p:commandButton type="submit" value="Save" action="#{userDetailController.doCreateNewUser()}" oncomplete="PF('userCreateDialog').hide()" update=":userForm:usersTable"/>
<p:commandButton value="Cancel" type="reset" resetValues="true" onclick="PF('userCreateDialog').hide()"/>
</h:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</p:card>
</div>
</ui:define>
</ui:composition>
JAVA FILE:
package at.qe.skeleton.ui.controllers;
import at.qe.skeleton.model.Room;
import at.qe.skeleton.model.User;
import at.qe.skeleton.model.UserRole;
import at.qe.skeleton.services.RoomService;
import at.qe.skeleton.services.UserService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* Controller for the user detail view.
*
* This class is part of the skeleton project provided for students of the
* courses "Software Architecture" and "Software Engineering" offered by the
* University of Innsbruck.
*/
#Component
#Scope("view")
public class UserDetailController implements Serializable {
#Autowired
transient private UserService userService;
#Autowired
private RoomService roomService;
/**
* Attribute to cache the currently displayed user
*/
transient private User user;
transient private User newUser = new User();
transient private List<Room> allRooms;
transient private UserRole role;
#PostConstruct
public void setup() {
allRooms = new ArrayList<>( roomService.getAllRooms());
}
/**
* Sets the currently displayed user and reloads it form db. This user is
* targeted by any further calls of
* {#link #doReloadUser()}, {#link #doSaveUser()} and
* {#link #doDeleteUser()}.
*
* #param user
*/
public void setUser(User user) {
System.out.println("trying to set User" );
this.user = user;
}
/**
* Returns the currently displayed user.
*
* #return
*/
public User getUser() {
return user;
}
public User getNewUser() {
return newUser;
}
public void setNewUser(User newUser) {
this.newUser = newUser;
}
public List<Room> getAllRooms() {
return allRooms;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
/**
* Action to force a reload of the currently displayed user.
*/
public void doReloadUser() {
user = userService.loadUser(user.getUsername());
}
public void doCreateNewUser(){
System.out.println("create the hell out");
newUser.setEnabled(true);
newUser.setRoles(new HashSet<UserRole>(){{
add(UserRole.EMPLOYEE);}});
this.userService.saveUser(newUser);
newUser = new User();
}
/**
* Action to save the currently displayed user.
*/
public void doSaveUser() {
System.out.println("Successfully saved user: " +user.getUsername() );
user = this.userService.saveUser(user);
}
/**
* Action to delete the currently displayed user.
*/
public void doDeleteUser() {
this.userService.deleteUser(user);
user = null;
}
}

Primefaces Bean Object isn't updated correctly

I've got the following issue. I have a XHTML:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
template="../layout.xhtml">
<ui:define name="header">
<div id="header">
Abfragen
</div>
</ui:define>
<ui:define name="main">
<p:toolbar>
<p:toolbarGroup>
<p:commandButton value="Neu" icon="pi pi-plus" actionListener="#{abfrageHandler.newAbfrage}"
update="manage-queries-content" oncomplete="PF('manageQueriesDialog').show()"
styleClass="ui-button-success" style="margin-right: .5rem">
<p:resetInput target=":ucmdbform:ucmdbtab:manage-ucmdb-queries-content"/>
</p:commandButton>
</p:toolbarGroup>
</p:toolbar>
<p:dataTable id="dt-queries" widgetVar="dtQueries" reflow="true" showGridlines="true" size="small"
var="querie" value="#{abfrageHandler.abfragen}">
<p:column headerText="Abfrage">
<h:outputText value="#{querie.name}" />
</p:column>
<p:column headerText="TQL">
<h:outputText value="#{querie.tql}" />
</p:column>
<p:column headerText="Zyklus">
<h:outputText value="#{querie.zyklus}" />
</p:column>
<p:column headerText="Typ">
<h:outputText value="#{querie.typ}" />
</p:column>
<p:column exportable="false">
<p:commandButton icon="pi pi-pencil" update="manage-queries-content"
oncomplete="PF('manageQueriesDialog').show()"
styleClass="edit-button rounded-button ui-button-success" process="#this">
<f:setPropertyActionListener value="#{querie}" target="#{abfrageHandler.selected}"/>
<p:resetInput target="manage-queries-content"/>
</p:commandButton>
<p:commandButton icon="pi pi-search" actionListener="#{abfrageHandler.startAbfrage(querie)}"
styleClass="edit-button rounded-button ui-button-success" process="#this">
</p:commandButton>
<p:commandButton class="ui-button-warning rounded-button" icon="pi pi-trash" process="#this"
oncomplete="PF('deleteQuerieDialog').show()">
<f:setPropertyActionListener value="#{querie}" target="#{abfrageHandler.selected}"/>
</p:commandButton>
</p:column>
</p:dataTable>
<p:dialog header="Abfrage" showEffect="fade" modal="true" width="600px"
widgetVar="manageQueriesDialog" responsive="true">
<p:outputPanel id="manage-queries-content" class="ui-fluid">
<p:outputPanel rendered="#{not empty abfrageHandler.selected}">
<div class="p-field">
<p:outputLabel for="abfName">Name</p:outputLabel>
<p:inputText id="abfName" value="#{abfrageHandler.selected.name}" required="true"/>
</div>
<div class="p-field">
<p:outputLabel for="abfTql">TQL</p:outputLabel>
<p:inputText id="abfTql" value="#{abfrageHandler.selected.tql}" required="true"/>
</div>
<div class="p-field">
<p:outputLabel for="abfZyklus">Zyklus</p:outputLabel>
<p:inputText id="abfZyklus" value="#{abfrageHandler.selected.zyklus}" required="true"/>
</div>
<div class="p-field">
<p:outputLabel for="#next">Abfrageart</p:outputLabel>
<p:selectOneMenu id="abfTyp" value="#{abfrageHandler.selected.typ}" required="false">
<f:selectItem itemLabel="Eins wählen" itemValue=""/>
<f:selectItems value="#{abfrageHandler.requestResolutions}" var="reso"
itemLabel="#{reso.toString()}" itemValue="#{reso}"/>
</p:selectOneMenu>
</div>
</p:outputPanel>
</p:outputPanel>
<f:facet name="footer">
<p:commandButton value="Speichern" icon="pi pi-check" actionListener="#{abfrageHandler.saveAbfrage}"
update="manage-queries-content" process="manage-queries-content #this"/>
<p:commandButton value="Abbruch" icon="pi pi-times" onclick="PF('manageQueriesDialog').hide()"
class="ui-button-secondary"/>
</f:facet>
</p:dialog>
<p:confirmDialog widgetVar="deleteQuerieDialog" showEffect="fade" width="300"
message="TQL wirklich löschen?" header="Bestätigen" severity="warn">
<p:commandButton value="Ja" icon="pi pi-check" actionListener="#{abfrageHandler.deleteParameter}"
process="#this" oncomplete="PF('deleteQuerieDialog').hide()"/>
<p:commandButton value="Nein" type="button" styleClass="ui-button-secondary" icon="pi pi-times"
onclick="PF('deleteQuerieDialog').hide()"/>
</p:confirmDialog>
</ui:define>
</ui:composition>
And the following bean in the backend:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.PrimeFaces;
import main.java.ucmdbtool.RequestResolutions;
import main.java.ucmdbtool.UcmdbAbfrageInteface;
import main.java.ucmdbtool.table.Abfrage;
import main.java.ucmdbtool.table.UcmdbAbfTableHandler;
#SuppressWarnings("serial")
#Named("abfrageHandler")
#ViewScoped
public class AbfrageHandler implements Serializable {
private List<Abfrage> abfragen = new ArrayList<>();
private Abfrage selected;
private RequestResolutions[] requestResolutions;
#PostConstruct
private void init() {
abfragen = UcmdbAbfTableHandler.getAbfragen();
requestResolutions = RequestResolutions.values();
}
public void newAbfrage() {
selected = new Abfrage();
}
public void saveAbfrage() {
if (selected.getPk() == null) {
selected.setPk(UUID.randomUUID());
UcmdbAbfTableHandler.insertAbfrage(selected);
abfragen.add(selected);
}
else {
UcmdbAbfTableHandler.updateAbfrage(selected);
}
PrimeFaces.current().executeScript("PF('manageQueriesDialog').hide()");
PrimeFaces.current().ajax().update("dt-queries");
}
public void startAbfrage(Abfrage abf) {
UcmdbAbfrageInteface.doRequest(abf);
}
public void deleteAbfrage() {
if(selected != null) {
UcmdbAbfTableHandler.deleteAbfrage(selected);
abfragen.remove(selected);
}
PrimeFaces.current().ajax().update("dt-queries");
}
public List<Abfrage> getAbfragen() { return abfragen; }
public Abfrage getSelected() { return selected; }
public RequestResolutions[] getRequestResolutions() { return requestResolutions; }
public void setSelected(Abfrage selected) { this.selected = selected; }
}
I've included all imports, because maybe one is off a false package. My problem is, if I click on new the dialog stays empty, because he thinks the object is empty. When I click on the edit button the object is loaded, but I can't save it because abfTyp is empty (it was required="true"), after I set required to false I could save, but my object had the old data and not the date I had changed. I have an almost similar page which is working fine and I can't find the difference. RequestResolutions is a stupid ENUM without any functions.
The dialog is empty when using "neu" because you create a new version of "selected" each time. The old data is reappearing on "edit" because the previous time failed the validation, but you immediately close the dialog. Then you use p:resetInput which resets back to the stored value. If the selectList value is empty, it means that what's coming from the data source does not match any values in the Enum select list that you provide.
I had a number of issues getting the sample to work... missing form, update= having bad references. But I think the main design issue is that you're not displaying any validation errors in the dialog - just closing the dialog window immediately. And, by the way, you should mostly be using action= on command buttons, not actionListener=. See here to understand why. All field validation will have passed before the action method gets executed.
I suggest the following amendments:
<p:commandButton value="Neu" icon="pi pi-plus" action="#{abfrageHandler.newAbfrage}"
update=":ucmdbform:manage-queries-content"
oncomplete="PF('manageQueriesDialog').show()"
styleClass="ui-button-success" style="margin-right: .5rem">
<!-- <p:resetInput target=":ucmdbform:manage-queries-content"/> -->
</p:commandButton>
.
.
<p:commandButton value="Speichern" icon="pi pi-check"
action="#{abfrageHandler.saveAbfrage}"
update=":ucmdbform:dt-queries :ucmdbform:manage-queries-content"
oncomplete="if ( args.saved == 1 ) { PF('manageQueriesDialog').hide()};"/>
Plus all actionListeners="..." --> action="..."; plus add p:message to all dialog fields that could possibly fail validation.
public void saveAbfrage() {
if (selected.getPk() == null) {
selected.setPk(UUID.randomUUID());
UcmdbAbfTableHandler.insertAbfrage(selected);
abfragen.add(selected);
} else {
UcmdbAbfTableHandler.updateAbfrage(selected);
}
PrimeFaces.current().ajax().addCallbackParam("saved", 1);
// PrimeFaces.current().ajax().update(":ucmdbform:dt-queries");
// PrimeFaces.current().executeScript("PF('manageQueriesDialog').hide();");
}

I'm trying to initilize an attribut in a bean with #viewScoped but it does not work

hello everyone I'm trying to build a webpage with two oneMenu the second one depending on the second one. My XHTML file is below as well as my bean.
when I try to create a new "structureAttache" I have the following problem
TemplateStructureAttache.xhtml #40,139 value="#{structureBean.structureAttache.intituleStructure}": Target Unreachable, 'structureAttache' returned null
and when I use the method initStruc to create a new structureAttache then I call it in the listener of my first ajax, I succeed to create a structureAttache but when I do it for the second time, it seems like the value already exit in the DB and it refuses please help me to solve this issue
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dresen.dresen.Beans;
import com.dresen.dresen.ServiceInterface.IArrondissementService;
import com.dresen.dresen.ServiceInterface.IStructureService;
import com.dresen.dresen.entities.Arrondissement;
import com.dresen.dresen.entities.StructureAttache;
import com.dresen.dresen.entities.CategorieStructure;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import com.dresen.dresen.ServiceInterface.ICategorieStructureService;
import com.dresen.dresen.ServiceInterface.IDepartementService;
import com.dresen.dresen.entities.Departement;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
/**
*
* #author Vivien Saa
*/
#ManagedBean
#ViewScoped
public class StructureBean implements Serializable{
#ManagedProperty(value = "#{IStructureService}")
private IStructureService iStructureService;
#ManagedProperty(value = "#{IArrondissementService}")
private IArrondissementService iArrondissementService;
#ManagedProperty(value = "#{ICategorieStructureService}")
private ICategorieStructureService iCategorieStructureService;
#ManagedProperty(value ="#{IDepartementService}")
private IDepartementService iDepartementService;
private long idDepartement;
private long idArrondissement;
private long idCategorieStructure;
private StructureAttache structureAttache;
private List<Arrondissement> listArrondissement;
private List<Departement> listDepartement;
private List<CategorieStructure> listCategorieStructure;
private Arrondissement arrondissement = new Arrondissement();
private CategorieStructure CategorieStructure = new CategorieStructure();
public StructureBean() {
structureAttache = new StructureAttache();
idDepartement = 0L;
idArrondissement = 0L;
idCategorieStructure = 0L;
}
public ICategorieStructureService getiCategorieStructureService() {
return iCategorieStructureService;
}
public void setiCategorieStructureService(ICategorieStructureService iCategorieStructureService) {
this.iCategorieStructureService = iCategorieStructureService;
}
public long getIdDepartement() {
return idDepartement;
}
public void setIdDepartement(long idDepartement) {
this.idDepartement = idDepartement;
}
public IDepartementService getiDepartementService() {
return iDepartementService;
}
public void setiDepartementService(IDepartementService iDepartementService) {
this.iDepartementService = iDepartementService;
}
public List<Departement> getListDepartement() {
return iDepartementService.findAllDepartement();
}
public void setListDepartement(List<Departement> listDepartement) {
this.listDepartement = listDepartement;
}
public long getIdCategorieStructure() {
return idCategorieStructure;
}
public void setIdCategorieStructure(long idCategorieStructure) {
this.idCategorieStructure = idCategorieStructure;
}
public List<CategorieStructure> getListCategorieStructure() {
return iCategorieStructureService.findAllCategorieStructure();
}
public void setListCategorieStructure(List<CategorieStructure> listCategorieStructure) {
this.listCategorieStructure = listCategorieStructure;
}
public IStructureService getiStructureService() {
return iStructureService;
}
public void setiStructureService(IStructureService iStructureService) {
this.iStructureService = iStructureService;
}
public IArrondissementService getiArrondissementService() {
return iArrondissementService;
}
public void setiArrondissementService(IArrondissementService iArrondissementService) {
this.iArrondissementService = iArrondissementService;
}
public long getIdArrondissement() {
return idArrondissement;
}
public void setIdArrondissement(long idArrondissement) {
this.idArrondissement = idArrondissement;
}
public StructureAttache getStructureAttache() {
return structureAttache;
}
public void setStructureAttache(StructureAttache structureAttache) {
this.structureAttache = structureAttache;
}
public List<Arrondissement> getListArrondissement() {
return iArrondissementService.findArrondissementByIdDepart(idDepartement);
}
public void setListArrondissement(List<Arrondissement> listArrondissement) {
this.listArrondissement = listArrondissement;
}
public Arrondissement getArrondissement() {
return arrondissement;
}
public void setArrondissement(Arrondissement arrondissement) {
this.arrondissement = arrondissement;
}
public CategorieStructure getCategorieStructure() {
return CategorieStructure;
}
public void setCategorieStructure(CategorieStructure CategorieStructure) {
this.CategorieStructure = CategorieStructure;
}
public void initStruc() {
structureAttache = new StructureAttache();
}
public StructureAttache createStructure(){
System.out.println("vvsssssssssvsssssssssssssssssssssssvv why don't you work");
arrondissement = iArrondissementService.findArrondissementById(idArrondissement);
CategorieStructure = iCategorieStructureService.findCategorieStructureById(idCategorieStructure);
structureAttache.setCategorieStructure(CategorieStructure);
structureAttache.setArrondissement(arrondissement);
return iStructureService.createStructureAttache(structureAttache);
}
public StructureAttache findStructureById(){
return iStructureService.findStructureAttacheById(structureAttache.getId());
}
public StructureAttache updateStructure(){
arrondissement = iArrondissementService.findArrondissementById(idArrondissement);
CategorieStructure = iCategorieStructureService.findCategorieStructureById(idCategorieStructure);
structureAttache.setCategorieStructure(CategorieStructure);
structureAttache.setArrondissement(arrondissement);
return iStructureService.updateStructureAttache(structureAttache);
}
public List<StructureAttache> findAllStructure(){
return iStructureService.findAllStructureAttache();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!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:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Application de gestion du personnel des services déconcentrés du MINESEC EXTREME NORD</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
<h:body>
<div id="menu">
<ui:include src="Menu.xhtml"/>
</div>
<f:view>
<p:dialog widgetVar="dlg" header=" Enregistrer une nouvel nouvelle Structure d'attache " hideEffect="explode" showEffect="explode" modal="true">
<h:form id="formAjouter" >
<p:panelGrid id="panelAjouter" columns="2">
<p:outputLabel value="Département:" />
<p:selectOneMenu id="depart" value="#{structureBean.idDepartement}" label="programme" filter="true" filterMatchMode="startsWith" panelStyle="width:220px">
<p:ajax event="change" update="arrond" />
<f:selectItem itemLabel="Selectioner le département" itemValue="" noSelectionOption="true" />
<f:selectItems var="custe1" value="#{structureBean.listDepartement}" itemLabel="#{custe1.intituleDepartement}" itemValue="#{custe1.id}" itemLabelEscaped="true" />
</p:selectOneMenu>
<p:outputLabel value="Arrondissement:" />
<p:selectOneMenu id="arrond" value="#{structureBean.idArrondissement}" filter="true" filterMatchMode="startsWith" panelStyle="width:220px">
<f:selectItems var="custe2" value="#{structureBean.listArrondissement}" itemLabel="#{custe2.intituleArrondissement}" itemValue="#{custe2.id}" itemLabelEscaped="true" />
</p:selectOneMenu>
<p:outputLabel value="Categorie de Structure:" />
<p:selectOneMenu value="#{structureBean.idCategorieStructure}" filter="true" filterMatchMode="startsWith" panelStyle="width:220px">
<f:selectItems var="custe3" value="#{structureBean.listCategorieStructure}" itemLabel="#{custe3.intituleCategorieStructure}" itemValue="#{custe3.id}" itemLabelEscaped="true" />
</p:selectOneMenu>
<p:outputLabel value="Intitule :" for="intitule" />
<p:inputText id="intitule" value="#{structureBean.structureAttache.intituleStructure}" title="intitulé" />
<p:outputLabel value="Code/Abréviation :" for="abrev" />
<p:inputText id="abrev" value="#{structureBean.structureAttache.codeStructure}" title="abrev"/>
<p:commandButton value="Enregistrer" action="#{structureBean.createStructure()}" oncomplete="PF('dlg').hide()" update=":tableForm:table" id="bout1" ajax="false" />
</p:panelGrid>
</h:form>
</p:dialog>
<p:dialog widgetVar="dl" header=" Modifier une structure d'attache" hideEffect="fold" showEffect="explode" resizable="true">
<h:form id="formModifier" enctype="multipart/form-data">
<p:panelGrid id="panelGModifier" columns="2">
<p:outputLabel value="Département:" />
<p:selectOneMenu id="depart" value="#{structureBean.idDepartement}" label="programme" filter="true" filterMatchMode="startsWith" panelStyle="width:220px">
<p:ajax event="change" update="arrond" />
<f:selectItem itemLabel="Selectioner le département" itemValue="" noSelectionOption="true" />
<f:selectItems var="custe1" value="#{structureBean.listDepartement}" itemLabel="#{custe1.intituleDepartement}" itemValue="#{custe1.id}" itemLabelEscaped="true" />
</p:selectOneMenu>
<p:outputLabel value="Arrondissement:" />
<p:selectOneMenu id="arrond" value="#{structureBean.idArrondissement}" filter="true" filterMatchMode="startsWith" panelStyle="width:220px">
<f:selectItems var="custe2" value="#{structureBean.listArrondissement}" itemLabel="#{custe2.intituleArrondissement}" itemValue="#{custe2.id}" itemLabelEscaped="true" />
</p:selectOneMenu>
<p:outputLabel value="Categorie de Structure:" />
<p:selectOneMenu value="#{structureBean.idCategorieStructure}" filter="true" filterMatchMode="startsWith" panelStyle="width:220px">
<f:selectItems var="custe3" value="#{structureBean.listCategorieStructure}" itemLabel="#{custe3.intituleCategorieStructure}" itemValue="#{custe3.id}" itemLabelEscaped="true" />
</p:selectOneMenu>
<p:outputLabel value="Intitule :" for="intitule" />
<p:inputText id="intitule" value="#{structureBean.structureAttache.intituleStructure}" title="intitulé" />
<p:outputLabel value="Code/Abréviation :" for="abrev" />
<p:inputText id="abrev" value="#{structureBean.structureAttache.codeStructure}" title="abrev"/>
<h:inputHidden id="number" value="#{structureBean.structureAttache.id}" />
<p:commandButton value="Modifier" action="#{structureBean.updateStructure()}" oncomplete="PF('dl').hide()" update=":tableForm:table" id="bout1" ajax="false" />
</p:panelGrid>
</h:form>
</p:dialog>
</f:view>
<f:view>
<h:form id='tableForm'>
<p:dataTable value="#{structureBean.findAllStructure()}" var="item" paginator="true" rows="10" paginatorTemplate=" {CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown} " id="table" rowsPerPageTemplate="5,10,15" selectionMode="single" selection="#{structureBean.structureAttache}" rowKey="#{item.id}">
<f:facet name="header">
La liste des Structures d'attache
</f:facet>
<p:column>
<f:facet name="header">
<h:outputText value="Structure"/>
</f:facet>
<h:outputText value="#{item.intituleStructure}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Code/Abréviation Structure"/>
</f:facet>
<h:outputText value="#{item.codeStructure}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Arrondissement"/>
</f:facet>
<h:outputText value="#{item.arrondissement.intituleArrondissement}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Département"/>
</f:facet>
<h:outputText value="#{item.arrondissement.departement.intituleDepartement}"/>
</p:column>
</p:dataTable>
<p:toolbar>
<f:facet name="left">
<p:commandButton type="push" onclick="PF('dlg').show();" value="Nouvelle Structure" icon="ui-icon-disk">
<p:ajax update=":formAjouter:panelAjouter" resetValues="true" />
</p:commandButton>
<p:commandButton onclick="PF('dl').show()" value="Modifier Structure" update=":formModifier:panelGModifier" icon="ui-icon-arrowrefresh-1-w"/>
<span class="ui-separator">
<span class="ui-icon ui-icon-grip-dotted-vertical" />
</span>
<p:commandButton type="push" title="Save" image="ui-icon-disk" />
<p:commandButton type="push" title="Update" icon="ui-icon-arrowrefresh-1-w"/>
<p:commandButton type="push" title="Print" image="ui-icon-print"/>
</f:facet>
</p:toolbar>
</h:form>
</f:view>
</h:body>
</html>
You can use a method to initialize your attributes as you would like to, then through an AJAX or and actionListener, you call the method that will do the job before you try to use the attribute.

panelGrid doesnt display inside dialog primefaces

My problem is simple and difficult at the same time.
I want to display some information in my p:dialog inside it. So I use my panel grid to do it. But it doesn't display the information and I don't know why. So here is the code of my page and my bean ;)
(I am using PrimeFaces 4.0, Mojara 2.1.6)
MessageBean
package ma.corporate.bean;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import ma.corporate.facade.MessageFacade;
import ma.corporate.model.Message;
#ManagedBean(name = "messageBean")
#SessionScoped
public class MessageBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private MessageFacade messageFacade;
private List<Message> messages;
private Message message;
private static int cpt=0;
//private Message message2;
public MessageBean() {
// messageFacade = new MessageFacade();
// messages = messageFacade.Lister();
/*
* if(messages==null) System.out.println("null"); else
* System.out.println(messages.get(0).getTextMessage());
*/
//message2=new Message();
message = new Message();
cpt++;
}
public List<Message> getMessages() {
// messages = messageFacade.Lister();
messageFacade = new MessageFacade();
messages = messageFacade.Lister();
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public void save() {
messageFacade.enregistrer(message);
}
public void Supprimer(Message message) {
messageFacade.supprimer(message);
messages = messageFacade.Lister();
}
public void init(Message message) {
//this.message.setEmail("aaaaaaaaaaaaaa");
//this.message.setNomComplet("bbbbbbbbbbbbbbbb");
//this.message.setTelephone("343232");
this.message = message;
System.out.println(this.message.getNomComplet());
System.out.println(cpt);
}
}
I wasn't able to make the code of my html page because of an error when I want to publish it.
<!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>
<h:form id="form1">
<p:growl id="messages" showDetail="true" />
<p:dataTable var="message" value="#{messageBean.messages}" id="table">
<p:column headerText="Nom Complet" style="width:200px">
<h:outputText value="#{message.nomComplet}" />
</p:column>
<p:column headerText="Telephone" style="width:200px">
<h:outputText value="#{message.telephone}" />
</p:column>
<p:column headerText="Email" style="width:200px">
<h:outputText value="#{message.email}" />
</p:column>
<p:column headerText="Objet" style="width:200px">
<h:outputText value="#{message.objet}" />
</p:column>
<p:column headerText="Options" style="width:200px">
<p:commandLink onclick="PF('dlg3').show();" process="#this"
actionListener="#{messageBean.init(message)}">
<h:graphicImage value="/Administration/img/afficher2.jpg"
style="width:60px;height:60px;" />
</p:commandLink>
<p:commandLink>
<h:graphicImage value="/Administration/img/reply.png"
style="width:60px;height:60px;" />
</p:commandLink>
<p:commandLink actionListener="#{messageBean.Supprimer(message)}"
ajax="true" update=":form1:table" process=":form1:table">
<p:graphicImage value="/Administration/img/spprimer.png"
style="width:60px;height:60px;" />
<p:confirm header="Confirmation" message="êtes vous sur?"
icon="ui-icon-alert" />
</p:commandLink>
<p:confirmDialog global="true" showEffect="fade"
hideEffect="explode">
<p:commandButton value="Yes" type="button"
styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
update="table" />
<p:commandButton value="No" type="button"
styleClass="ui-confirmdialog-no" icon="ui-icon-close" />
</p:confirmDialog>
</p:column>
</p:dataTable>
<!-- the problem is the dialog below -->
<p:dialog header="Message" widgetVar="dlg3" showEffect="explode"
hideEffect="bounce" resizable="true" >
<h:form>
<p:panelGrid columns="2">
<h:outputLabel value="Nom Complet: " />
<h:inputTextarea id="firstname" value="#{messageBean.message.nomComplet}" />
<h:outputLabel value="Telephone :" />
<h:outputLabel id="Telephone"
value="#{messageBean.message.telephone}" />
<h:outputLabel value="Email :" />
<p:outputLabel id="Email" value="#{messageBean.message.email}" />
<h:outputLabel value="Objet :" />
<h:outputLabel id="Objet" value="#{messageBean.message.objet}" />
<h:outputLabel value="TextMessage :" />
<h:outputLabel id="TextMessage"
value="#{messageBean.message.textMessage}" />
</p:panelGrid>
</h:form>
</p:dialog>
</h:form>
<ui:remove>
<!--<p:dialog widgetVar="dlg2" global="true" showEffect="fade"
hideEffect="explode">
<h:panelGrid columns="1">
<h:outputText value="êtes vous sur?" />
<p:separator />
<h:panelGrid columns="2">
<p:commandButton value="Yes" type="button"
styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />
<p:commandButton value="No" type="button"
styleClass="ui-confirmdialog-no" icon="ui-icon-close" />
</h:panelGrid>
</h:panelGrid>
</p:dialog> -->
</ui:remove>
Look like an update issue. The bean get the value from xhtml page ? If he get it try to replace this two line:
<p:commandLink onclick="PF('dlg3').show();" process="#this" actionListener="#{messageBean.init(message)}">
<p:dialog header="Message" widgetVar="dlg3" showEffect="explode" hideEffect="bounce" resizable="true">
by :
<p:commandLink onclick="PF('dlg3').show();" update=":form1:dlg3" process="#this" actionListener="#{messageBean.init(message)}">
<p:dialog header="Message" id="dlg3" widgetVar="dlg3" showEffect="explode" hideEffect="bounce" resizable="true">

file upload within a wizard in primefaces - uploaded file does not showing up?

I use the Primefaces manual example for a wizard, and replace one of the tabs by a simple file upload form. I have all the necessary libraries and filter in web-inf for the file upload to work. Running the project with Netbeans does not show any error (the wizard is displayed and the UI responds), but the file is not uploaded and I get no system message from my fileBean class. Any clue where I make a mistake? Is something wrong with my nested form in the index.html? Thx!
index.xhtml:
<?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:p="http://primefaces.org/ui">
<h:head>
<title>The rings of scholarship</title>
</h:head>
<h:body>
<h:form>
<p:growl id="growl" sticky="true" showDetail="true"/>
<p:wizard widgetVar="wiz"
flowListener="#{userWizard.onFlowProcess}">
<p:tab id="personal" title="Personal">
<p:panel header="Personal Details">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value" styleClass="grid">
<h:outputText value="Firstname: *" />
<p:inputText required="true" label="Firstname"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: *" />
<p:inputText required="true" label="Lastname"
value="#{userWizard.user.lastname}" />
<h:outputText value="Age: " />
<p:inputText value="#{userWizard.user.age}" />
<h:outputText value="Skip to last: " />
<h:selectBooleanCheckbox value="#{userWizard.skip}" />
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="upload" title="File upload">
<p:panel header="File upload">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{fileBean.file}" mode="simple" />
<p:commandButton value="Submit" action="#{fileBean.save}" ajax="false"/>
</h:form>
</h:panelGrid>
<h:outputText value="Skip to last: " />
<h:selectBooleanCheckbox value="#{userWizard.skip}" />
</p:panel>
</p:tab>
<p:tab id="contact" title="Contact">
<p:panel header="Contact Information">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:outputText value="Email: *" />
<p:inputText required="true" label="Email"
value="#{userWizard.user.email}" />
<h:outputText value="Phone: " />
<p:inputText value="#{userWizard.user.phone}"/>
<h:outputText value="Additional Info: " />
<p:inputText value="#{userWizard.user.info}"/>
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="confirm" title="Confirmation">
<p:panel header="Confirmation">
<h:panelGrid id="confirmation" columns="6">
<h:outputText value="Firstname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.lastname}"/>
<h:outputText value="Age: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.age}" />>
<h:outputText value="Email: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.email}" />
<h:outputText value="Phone " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.phone}"/>
<h:outputText value="Info: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.info}" />
<h:outputText />
<h:outputText />
</h:panelGrid>
<p:commandButton value="Submit" update="growl"
actionListener="#{userWizard.save}"/>
</p:panel>
</p:tab>
</p:wizard>
</h:form>
</h:body>
</html>
fileBean:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import org.apache.commons.io.IOUtils;
import org.primefaces.model.UploadedFile;
#ManagedBean
#ViewScoped
public class FileBean implements Serializable{
private UploadedFile file;
/**
* Creates a new instance of FileBean
*/
public FileBean() {
}
public UploadedFile getFile() {
System.out.println("we get file");
return file;
}
public void setFile(UploadedFile file) throws FileNotFoundException, IOException {
System.out.println("we set file");
this.file = file;
}
public void save() throws IOException {
System.out.println("we save file");
IOUtils.copy(file.getInputstream(), new FileOutputStream("D:\\" + file.getFileName()));
BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputstream()));
String currLine = br.readLine();
Integer counterLines = 0;
while (currLine != null && counterLines < 5) {
System.out.println("currLine is: " + currLine);
counterLines++;
}
}
}
UserWizard:
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.event.FlowEvent;
#ManagedBean
#ViewScoped
public class UserWizard implements Serializable{
private User user = new User();
private boolean skip;
private static final Logger logger = Logger.getLogger(UserWizard.class.getName());
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void save(ActionEvent actionEvent) {
//Persist user
FacesMessage msg = new FacesMessage("Successful", "Welcome :" + user.getFirstname());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public boolean isSkip() {
return skip;
}
public void setSkip(boolean skip) {
this.skip = skip;
}
public String onFlowProcess(FlowEvent event) {
logger.log(Level.INFO, "Current wizard step:{0}", event.getOldStep());
logger.log(Level.INFO, "Next step:{0}", event.getNewStep());
if (skip) {
skip = false; //reset in case user goes back
return "confirm";
} else {
return event.getNewStep();
}
}
}
Start by getting rid of the nested forms... you got one surrounding the wizard and one inside the <p:tab id="upload" title="File upload">
Try removing the inner form from the tab and wrap the wizard with <h:form enctype="multipart/form-data">

Resources