Selected Row doesnt get selected in datalist JSF - jsf

i m using datalist in jsf with primefaces , i m facing problem backing bean class field of selected object does not get updated to selected row of datalist ,it is always giving null object. Here is the code
view File :
`<?xml version="1.0"?>`
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head />
<h:body>
<h:form>
<p:dataList value="#{tableBean.getList()}" var="job" id="cars"
paginator="true" rows="5" effectSpeed="fast"
paginatorTemplate="{PreviousPageLink} {CurrentPageReport} {NextPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5" type="none">
<f:facet name="header">
Applicants List
</f:facet>
<p:column>
<div style="width: 200px">
<h:outputText value="Name:" style="margin-left:10px" />
<h:outputText value="#{job.name}" style="margin-left:10px" />
<br />
<h:outputText value="Applied for:" style="margin-left:10px" />
<h:outputText value="#{job.jobtitle}" style="margin-left:10px" />
<br />
<h:outputText value="Degree:" style="margin-left:10px" />
<h:outputText value="#{job.degree}" style="margin-left:10px" />
<br />
<h:outputText value="Experience:" style="margin-left:10px" />
<h:outputText value="#{job.experience}" style="margin-left:10px" />
<br />
<h:outputText value="Contact:" style="margin-left:10px" />
<h:outputText value="#{job.contact}" style="margin-left:10px" />
<br />
<h:commandLink value="Call for Interview" style="margin-left:10px"></h:commandLink>
</div>
<br/>
<p:commandButton icon="ui-icon-search"
actionListener="#{tableBean.printView}" title="View Detail">
<f:setPropertyActionListener value="#{job}"
target="#{tableBean.selectedJob}" />
</p:commandButton>
<p:separator id="separator" />
</p:column>
</p:dataList>
</h:form>
</h:body>
</f:view>
table bean class:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import DAO.JobApplicationDao;
import DTO.JobApplicationDto;
#ManagedBean
#ViewScoped
public class TableBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public JobApplicationDto selectedJob;
public TableBean() {
}
public List<JobApplicationDto> getList() {
List<JobApplicationDto> joblist = new ArrayList<JobApplicationDto>();
JobApplicationDao dao = new JobApplicationDao();
joblist =dao.getDroppedCv();
return joblist;
}
public JobApplicationDto getSelectedJob() {
return selectedJob;
}
public void setSelectedJob(JobApplicationDto selectedJob) {
this.selectedJob = selectedJob;
}
public void printView(ActionEvent event) {
try{
System.out.print("Selected Person "+getSelectedJob.getName());
}catch(Exception e){
}
}
}

You should use the setPropertyActionListener with action . Listeners are called before your action is invoked. It seems like the setPropertyActionListener is getting called after actionListener.
Change actionListener="#{tableBean.printView}" to action="#{tableBean.printView}"
and method to
public void printView() {
try{
System.out.print("Selected Person "+getSelectedJob.getName());
}catch(Exception e){
}
}
see this for better understanding of what to use ,
http://balusc.blogspot.com/2006/06/communication-in-jsf.html

You can use datatable selection like this
<p:dataList value="#{tableBean.getList()}" selection="#{tableBean.selectedJob}" var="job" id="cars"
paginator="true" rows="5" effectSpeed="fast"
paginatorTemplate="{PreviousPageLink} {CurrentPageReport} {NextPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5" type="none">

Related

PrimeFaces Drag & Drop not working if other portlets contain <form> tags

If I have a Liferay page which includes a Liferay Web Content Display with a form tag and then a PrimeFaces portlet with p:droppable and p:draggable, the Drag & Drop functionality does not work.
My XHTML:
<?xml version="1.0"?>
<f:view xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head />
<h:body>
<h:form id="carForm">
<p:fieldset id="availableCarsField" legend="AvailableCars">
<p:dataGrid id="availableCars" var="car" value="#{dndCarsView.cars}" columns="3">
<p:panel id="pnl" header="#{car.id}" style="text-align:center">
<h:panelGrid columns="1" style="width:100%">
<h:outputText value="#{car.id}" />
</h:panelGrid>
</p:panel>
<p:draggable for="pnl" revert="true" handle=".ui-panel-titlebar" stack=".ui-panel" />
</p:dataGrid>
</p:fieldset>
<p:fieldset id="selectedCars" legend="Selected Cars" style="margin-top:20px">
<p:outputPanel id="dropArea">
<h:outputText value="!!!Drop here!!!" rendered="#{empty dndCarsView.droppedCars}" style="font-size:24px;" />
<p:dataTable id="selectedCarsTable" var="car" value="#{dndCarsView.droppedCars}"
rendered="#{not empty dndCarsView.droppedCars}">
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
<p:column style="width:32px">
<p:commandButton update=":carForm:display" oncomplete="PF('carDialog').show()" icon="ui-icon-search">
<f:setPropertyActionListener value="#{car}" target="#{dndCarsView.selectedCar}" />
</p:commandButton>
</p:column>
</p:dataTable>
</p:outputPanel>
</p:fieldset>
<p:droppable for="selectedCars" tolerance="touch" activeStyleClass="ui-state-highlight" datasource="availableCars"
onDrop="handleDrop">
<p:ajax listener="#{dndCarsView.onCarDrop}" update="dropArea availableCars" />
</p:droppable>
<p:dialog header="Car Detail" widgetVar="carDialog" resizable="false" draggable="false" showEffect="fade"
hideEffect="fade" modal="true">
<p:outputPanel id="display">
<h:panelGrid columns="2" cellpadding="5" rendered="#{not empty dndCarsView.selectedCar}">
<f:facet name="header">
<p:graphicImage name="/demo/images/car/#{dndCarsView.selectedCar.brand}.gif" />
</f:facet>
<h:outputText value="Id" />
<h:outputText value="#{dndCarsView.selectedCar.id}" style="font-weight:bold" />
<h:outputText value="Year:" />
<h:outputText value="#{dndCarsView.selectedCar.year}" style="font-weight:bold" />
<h:outputText value="Brand" />
<h:outputText value="#{dndCarsView.selectedCar.brand}" style="font-weight:bold" />
<h:outputText value="Color:" />
<h:outputText value="#{dndCarsView.selectedCar.color}" style="font-weight:bold" />
</h:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</h:body>
</f:view>
My Bean:
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.ViewScoped;
import org.primefaces.event.DragDropEvent;
#ManagedBean(name = "dndCarsView")
#ViewScoped
public class DNDCarsView implements Serializable {
private List<Car> cars;
private List<Car> droppedCars;
private Car selectedCar;
#PostConstruct
public void init() {
cars = new ArrayList<Car>();
cars.add(new Car(1, 2001, "toyota", "black"));
cars.add(new Car(2, 2002, "honda", "yello"));
cars.add(new Car(3, 2003, "ferrari", "white"));
cars.add(new Car(4, 2004, "bmw", "green"));
cars.add(new Car(5, 2005, "suzuki", "blue"));
cars.add(new Car(6, 2006, "mazda", "brown"));
cars.add(new Car(7, 2007, "audi", "halfwhie"));
cars.add(new Car(8, 2008, "aqua", "neroon"));
droppedCars = new ArrayList<Car>();
}
public void onCarDrop(DragDropEvent ddEvent) {
Car car = ((Car) ddEvent.getData());
droppedCars.add(car);
cars.remove(car);
}
public List<Car> getCars() {
return cars;
}
public List<Car> getDroppedCars() {
return droppedCars;
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
}
You are running into PrimeFaces Issue #3265: PrimeFaces Draggable/Droppable submits Ajax requests via the wrong form. A simple workaround is to explicitly declare the form that you wish to use for Draggable/Droppable Ajax requests (using h:form's binding and p:ajax's form attributes):
<h:form id="carForm" binding="#{carForm}">
<!-- Your code here.... -->
<p:droppable for="selectedCars" tolerance="touch"
activeStyleClass="ui-state-highlight" datasource="availableCars"
onDrop="handleDrop">
<p:ajax listener="#{dndCarsView.onCarDrop}"
update="dropArea availableCars" form="#{carForm.clientId}" />
</p:droppable>
</h:form>

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.

f:setPropertyActionListener only works in view not in backing bean

I try to get the information about the clicked button in a <p:datalist>, but it doesn't work.
My View:
<ui:composition 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" template="/WEB-INF/template.xhtml">
<ui:define name="head">
<title>Hash Generator</title>
</ui:define>
<ui:define name="content">
<h:form id="hashForm">
<p:dataList id="hashList" value="#{hashGeneratorBean.hashList}" var="entry" rowIndexVar="idx" itemType="none">
<p:column>
<h:outputText value="#{idx + 1}" />
<h:inputText value="#{entry.clearText}" />
<h:inputText value="#{entry.hashedText}" readonly="true" disabled="true" size="#{entry.hashedText.length() + 15}"/>
<p:commandButton id="addRow" actionListener="#{hashGeneratorBean.addRow}" icon="ui-icon-plus" title="Icon Only" update="hashList">
<f:setPropertyActionListener value="#{entry}" target="#{hashGeneratorBean.selectedRow}" />
</p:commandButton>
<p:commandButton id="debugBtn" icon="ui-icon-disc" title="Icon Only" update=":hashForm:display" oncomplete="PF('dlg').show()">
<f:setPropertyActionListener value="#{entry}" target="#{hashGeneratorBean.selectedRow}" />
</p:commandButton>
</p:column>
</p:dataList>
<p:commandButton actionListener="#{hashGeneratorBean.hash}" value="Generate Hashes" update="hashList" />
<p:dialog modal="true" widgetVar="dlg">
<h:panelGrid id="display" columns="2">
<f:facet name="header">
<h:outputText value="#{hashGeneratorBean.selectedRow.clearText}" />
</f:facet>
<h:outputText value="#{hashGeneratorBean.selectedRow.hashedText}" />
</h:panelGrid>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
My Controller:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
#ManagedBean
#ViewScoped
public class HashGeneratorBean {
private List<HashDTO> hashList = new ArrayList<HashDTO>();
private HashDTO selectedRow = new HashDTO();
#PostConstruct
public void init() {
hashList.add(new HashDTO());
}
public void addRow(ActionEvent ae){
hashList.add(new HashDTO());
}
public void hash(ActionEvent ae){
for (HashDTO entry : hashList){
entry.setHashedText(generateHash(entry.getClearText()));
}
}
/**
* Hashes the given password with SHA-256
* #param password
* #return passwordHash
*/
public static String generateHash(String password) {
return Hashing.sha256().hashString(password, Charsets.UTF_8).toString();
}
public List<HashDTO> getHashList() {
return hashList;
}
public void setHashList(List<HashDTO> hashList) {
this.hashList = hashList;
}"
public HashDTO getSelectedRow() {
return selectedRow;
}
public void setSelectedRow(HashDTO selectedRow) {
this.selectedRow = selectedRow;
}
}
If I click the "debugBtn"-button the dialog popups up and shows the correct information about the row. But If I click the "addRow"-button the data in the managed-bean isn't filled correct. The selectedRow-property allways stores the last added row from the hashList-property.
I found the solution.
The PropertyActionListener is called after the ActionListener.
the Solution is to use "Action" or register the the ActionListener with and a Extended Action Listener

<p:dataTable> single selection not appearing in dialog

I have trouble displaying my property details on the dialog, after generating the table. Results are shown, but the selected row is not shown on dialog. I have taken over the example from primefaces show case.
<!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>TODO supply a title</title>
<h:outputStylesheet library="css" name="styles.css" />
</h:head>
<h:body>
Dear customer!
<li>#{userDataManager.displayHotelTypeChoice(userDataManager.hotelChoice)}
</li>
<li>#{userDataManager.displayPaxChoice(userDataManager.pax)}
</li>
<li>You have chosen to check in : #{userDataManager.displayCheckinDate(userDataManager.checkinDate)}
</li>
<li>You have chosen to check out : #{userDataManager.displayCheckoutDate(userDataManager.checkoutDate)}
</li>
<li>Total Days of Stay : #{userDataManager.countNightsBetween(userDataManager.checkinDate,userDataManager.checkoutDate)}
</li>
<li>Total Nights of Stay : #{userDataManager.nights}
</li>
<br>
</br>
<h:form id="form">
<p:dataTable id="hotels" var="room" value="#{propertyDataTable.searchByHotelType
(userDataManager.hotelChoice, userDataManager.pax)}"
rowKey="#{room.propertyID}"
selection="#{propertyDataTable.selectedProperty}"
selectionMode="single"
resizableColumns="true">
<f:facet name="header">
#{userDataManager.displayHotelTypeChoice(userDataManager.hotelChoice)}<br></br>
Please select only one choice
</f:facet>
<p:column headerText="Property ID" >
#{room.propertyID}
</p:column>
<p:column headerText="Accommodation" >
#{room.accommodation}
</p:column>
<p:column headerText="Pax" >
#{room.pax}
</p:column>
<p:column headerText="Stars" >
#{room.stars}
</p:column>
<p:column headerText="Type" >
#{room.type}
</p:column>
<f:facet name="footer">
In total there are #{propertyDataTable.listSize(propertyDataTable.
searchByHotelType(userDataManager.hotelChoice,
userDataManager.pax))} hotels.
<p:commandButton id="viewButton" value="View" icon="ui-icon-search"
update=":form:display" oncomplete="hotelDialog.show()">
</p:commandButton>
</f:facet>
</p:dataTable>
<p:dialog id="dialog" header="Hotel Detail" widgetVar="hotelDialog" resizable="false"
width="200" showEffect="clip" hideEffect="fold">
<h:panelGrid id="display" columns="2" cellpadding="4">
<f:facet name="header">
<!--<p:graphicImage value="/resources/images/#{propertyDataTable.selectedProperty.type}.jpg"/>-->
<p:graphicImage value="/resources/images/Grand.jpg"/>
</f:facet>
<h:outputText value="Accommodation:" />
<h:outputText value="#{propertyDataTable.selectedProperty.accommodation }" />
<h:outputText value="Feature:" />
<h:outputText value="#{propertyDataTable.selectedProperty.feature}" />
<h:outputText value="Stars:" />
<h:outputText value="#{propertyDataTable.selectedProperty.stars}" />
</h:panelGrid>
</p:dialog>
</h:form>
<br></br>
<br></br>
<h:commandButton value="Book"
action="#{navigationController.showPage()}" >
<f:param name="page" value="book" />
</h:commandButton>
<br></br>
<h:commandButton value="HOME"
action="#{navigationController.showPage()}" >
<f:param name="page" value="home" />
</h:commandButton>
</h:body>
</html>
package dataTable;
import irms.entity.accommodation.Property;
import irms.entity.accommodation.Room;
import irms.session.accommodation.PropertySession;
import irms.session.accommodation.ReservationSession;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
/**
*
* #author Lawrence
*/
#ManagedBean(name = "propertyDataTable")
#ViewScoped
public class PropertyDataTable implements Serializable{
#EJB
private ReservationSession reservationSession;
#EJB
private PropertySession propertySession;
private List<Property> propertyList;
private int choice;
private Property selectedProperty;
private List<Room> list = new ArrayList();
public PropertyDataTable() {
}
public List<Property> getAllRooms() {
return reservationSession.getAllRooms();
}
public List<Property> searchByHotelType(String hotelType, Integer pax) {
this.propertyList = propertySession.searchByHotelType(hotelType, pax);
return propertyList;
}
public int listSize(List<Property> list){
return list.size();
}
public Room getRoom(String propertyID, Integer roomID) {
return propertySession.findRoom(propertyID, roomID);
}
public List<Room> getRoomList(String propertyID){
return propertySession.getRoomList(propertyID);
}
public ReservationSession getReservationSession() {
return reservationSession;
}
public void setReservationSession(ReservationSession reservationSession) {
this.reservationSession = reservationSession;
}
public PropertySession getPropertySession() {
return propertySession;
}
public void setPropertySession(PropertySession propertySession) {
this.propertySession = propertySession;
}
public List<Property> getPropertyList() {
return propertyList;
}
public void setPropertyList(List<Property> propertyList) {
this.propertyList = propertyList;
}
public int getChoice() {
return choice;
}
public void setChoice(int choice) {
this.choice = choice;
}
public Property getSelectedProperty() {
return selectedProperty;
}
public void setSelectedProperty(Property selectedProperty) {
this.selectedProperty = selectedProperty;
}
public List<Room> getList() {
return list;
}
public void setList(List<Room> list) {
this.list = list;
}
}
You Must add ActionListener in your viewButton commandButton
change your xhtml page like this:
<!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>TODO supply a title</title>
<h:outputStylesheet library="css" name="styles.css" />
</h:head>
<h:body>
Dear customer!
<li>#{userDataManager.displayHotelTypeChoice(userDataManager.hotelChoice)}
</li>
<li>#{userDataManager.displayPaxChoice(userDataManager.pax)}
</li>
<li>You have chosen to check in : #{userDataManager.displayCheckinDate(userDataManager.checkinDate)}
</li>
<li>You have chosen to check out : #{userDataManager.displayCheckoutDate(userDataManager.checkoutDate)}
</li>
<li>Total Days of Stay : #{userDataManager.countNightsBetween(userDataManager.checkinDate,userDataManager.checkoutDate)}
</li>
<li>Total Nights of Stay : #{userDataManager.nights}
</li>
<br>
</br>
<h:form id="form">
<p:dataTable id="hotels" var="room" value="#{propertyDataTable.searchByHotelType
(userDataManager.hotelChoice, userDataManager.pax)}"
rowKey="#{room.propertyID}"
resizableColumns="true">
<f:facet name="header">
#{userDataManager.displayHotelTypeChoice(userDataManager.hotelChoice)}<br></br>
Please select only one choice
</f:facet>
<p:column headerText="Property ID" >
#{room.propertyID}
</p:column>
<p:column headerText="Accommodation" >
#{room.accommodation}
</p:column>
<p:column headerText="Pax" >
#{room.pax}
</p:column>
<p:column headerText="Stars" >
#{room.stars}
</p:column>
<p:column headerText="Type" >
#{room.type}
</p:column>
<f:facet name="footer">
In total there are #{propertyDataTable.listSize(propertyDataTable.
searchByHotelType(userDataManager.hotelChoice,
userDataManager.pax))} hotels.
<p:commandButton id="viewButton" value="View" icon="ui-icon-search"
update=":form:display" oncomplete="hotelDialog.show()">
<f:setPropertyActionListener value="#{room}" target="#{propertyDataTable.selectedProperty}" />
</p:commandButton>
</f:facet>
</p:dataTable>
<p:dialog id="dialog" header="Hotel Detail" widgetVar="hotelDialog" resizable="false"
width="200" showEffect="clip" hideEffect="fold">
<h:panelGrid id="display" columns="2" cellpadding="4">
<f:facet name="header">
<!--<p:graphicImage value="/resources/images/#{propertyDataTable.selectedProperty.type}.jpg"/>-->
<p:graphicImage value="/resources/images/Grand.jpg"/>
</f:facet>
<h:outputText value="Accommodation:" />
<h:outputText value="#{propertyDataTable.selectedProperty.accommodation }" />
<h:outputText value="Feature:" />
<h:outputText value="#{propertyDataTable.selectedProperty.feature}" />
<h:outputText value="Stars:" />
<h:outputText value="#{propertyDataTable.selectedProperty.stars}" />
</h:panelGrid>
</p:dialog>
</h:form>
<br></br>
<br></br>
<h:commandButton value="Book"
action="#{navigationController.showPage()}" >
<f:param name="page" value="book" />
</h:commandButton>
<br></br>
<h:commandButton value="HOME"
action="#{navigationController.showPage()}" >
<f:param name="page" value="home" />
</h:commandButton>
</h:body>
</html>

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