Send data primefaces to another page - primefaces

I´m newbie in primefaces, i have done a datatable and i show it in index.xhtml i have got a button when i push, it show the selection datatable (dialog) but i don´t know how to send the select datatable to another page. Sorry I´m learning english, thx.
index.xhtml
<p:dataTable id="singleDT" var="emp" value="#{empresaBean.getEmpresaList()}" selectionMode="single"
scrollable="true" scrollHeight="400" selection="#{empresaBean.selectedEmpresa}" rowKey="#{emp.CLAVE}">
<f:facet name="header">
Lista de Empresas
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{emp.CLAVE}" />
</p:column>
<p:column headerText="Nombre Empresa">
<h:outputText value="#{emp.NOMBRE}" />
</p:column>
<p:column headerText="AÑO">
<h:outputText value="#{emp.EJERCICIO}" />
</p:column>
<f:facet name="footer">
<p:button outcome="/pages/menu/menuPrincipal.xhtml" value="Seleccionar" title="Ir Menu">
</p:button>
<p:commandButton value="View" image="ui-icon ui-icon-search"
oncomplete="empresaDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="empresaDialog" resizable="false"
width="200" showEffect="clip" hideEffect="fold">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Clave:" />
<h:outputText value="#{empresaBean.selectedEmpresa.CLAVE}" />
<h:outputText value="Año:" />
<h:outputText value="#{empresaBean.selectedEmpresa.NOMBRE}" />
<h:outputText value="Año:" />
<h:outputText value="#{empresaBean.selectedEmpresa.EJERCICIO}" />
</h:panelGrid>
</p:dialog>
</h:form>
</h:body>
EmpresaBean
#ManagedBean(name="empresaBean")
#Scope
#Component
public class EmpresaBean {
#Autowired
private EmpresaService empresaService;
private Empresa empresa;
private Empresa selectedEmpresa;
private List<Empresa> empresasSmall;
public EmpresaService getEmpresaService() {
return empresaService;
}
public Empresa getSelectedEmpresa() {
return selectedEmpresa;
}
public void setSelectedEmpresa(Empresa selectedEmpresa) {
this.selectedEmpresa = selectedEmpresa;
}
public void setEmpresaService(EmpresaService empresaService) {
this.empresaService = empresaService;
}
public EmpresaBean(){
empresa = new Empresa();
// empresasSmall=new ArrayList<Empresa>();
// list.add(new Empresa(getEmpresaList());
}
/*
public void addEmpresa(){
empresaService.add(empresa);
empresa = new Empresa();
} */
public List<Empresa> getEmpresaList(){
return empresaService.getAll();
}
public Empresa getEmpresa() {
return empresa;
}
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
}

You can not send html to another page (dialog). You should push only data, which will be used on another page.
To push data from datatable (which is considered to be a List) you should use #ManagedProperty annotation.
Assuming you have index page:
#ManagedBean(name="index")
#SessionScoped
public class IndexPage implements Serializable {
private List<String> values;
//getter and setter
}
and you have another page, where you would like to use that list:
#ManagedBean(name="nextPage")
#SessionScoped
public class AnotherPage implements Serializable {
#ManagedProperty(value="#{index.values}")
private List<String> forwardedList; //list with values form index page
//getter and setter
}
http://www.mkyong.com/jsf2/injecting-managed-beans-in-jsf-2-0/
UPD: if you would like to forward a row, but not a list, you should just make minor change in AnotherPage class:
#ManagedBean(name="nextPage")
#SessionScoped
public class AnotherPage implements Serializable {
#ManagedProperty(value="{empresaBean.selectedEmpresa}")
private Empresa selectedValue; //value from selected row in your table
//getter and setter
}

Related

command button charge empty values

i'm using jsf2.2 primefaces 6.0 and i create clickable interface that shows the details of the demand throw clicking on the table.After that, i create a command button that shown on 2 specific condition(only when the demand is "Encours" or "Amodifier").My problem is when i try to load the demand details throw "modifier" button it charges empty values.It loads full values only when i preceed it with clicking on the table before to show the demand details.
I need help to solve this problem because i need "modifier" button to update data after that.
xhtml page:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui" xmlns:jsf="http://xmlns.jcp.org/jsf"
xmlns:pt="http://xmlns.jcp.org/jsf/passthrought"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
template="/facelets/template.xhtml">
<ui:define name="pageTitle">espace employer</ui:define>
<ui:define name="content">
<ul class="breadcrumb">
<li><i class="ace-icon fa fa-home home-icon"></i> Acceuil</li>
<li class="active">espace Employé</li>
</ul>
<!-- /.breadcrumb -->
</ui:define>
<ui:define name="pageHeader">
<h1></h1>
</ui:define>
<ui:define name="pageContent">
<h:form id="form">
<p:panel header="Mes Demandes">
<p:dataTable id="tt1" selectionMode="single" rowKey="#{d.id}"
value="#{demandeBean.allDemandesParEmployer}" var="d"
emptyMessage="Aucune demande">
<p:ajax event="rowSelect" listener="#{demandeBean.onRowSelect}"
oncomplete="PF('d3').show()" update=":form:d3" />
<p:column headerText="Date">
<h:outputText value="#{d.dateDeDepot}">
<f:convertDateTime pattern="dd/MM/yyyy HH:mm:ss"
timeZone="GMT+1:00" />
</h:outputText>
</p:column>
<p:column headerText="État">
<h:outputText value="#{d.etatDemande}" />
</p:column>
<p:column style="text-align: center" headerText="Visualiser">
<p:commandButton update="#form" oncomplete="PF('diag').show()"
icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{d}"
target="#{demandeBean.demandeSelectionnee}" />
</p:commandButton>
</p:column>
<p:column headerText="Action">
<p:commandButton value="Modifier" icon="ui-icon-disk" onclick="PF('d3').show();"
rendered="#{d.etatDemande == 'ENCOURS'|| d.etatDemande == 'AMODIFIER'}">
<f:setPropertyActionListener value="#{d}"
target="#{demandeBean.demandeSelectionnee}" />
</p:commandButton>
</p:column>
</p:dataTable>
</p:panel>
<p:panel rendered="#{not empty demandeBean.allDemandesParAssures}"
header="Mes assurés demandes">
<p:dataTable value="#{demandeBean.allDemandesParAssures}" var="d"
selectionMode="single" rowKey="#{d.id}"
emptyMessage="Aucune demande">
<p:ajax event="rowSelect" listener="#{demandeBean.onRowSelect}"
oncomplete="PF('d2').show()" update=":form:d2" />
<p:column headerText="État">
<h:outputText value="#{d.dateDeDepot}">
<f:convertDateTime pattern="dd/MM/yyyy HH:mm:ss"
timeZone="GMT+1:00" />
</h:outputText>
</p:column>
<p:column headerText="Assuré">
<h:outputText value="#{d.employer.name} #{d.employer.prenom}" />
</p:column>
<p:column headerText="État">
<h:outputText value="#{d.etatDemande}" />
</p:column>
<p:column style="text-align: center" headerText="Visualiser">
<p:commandButton update="#form" oncomplete="PF('diag').show()"
icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{d}"
target="#{demandeBean.demandeSelectionnee}" />
</p:commandButton>
</p:column>
</p:dataTable>
</p:panel>
<p:dialog header="Détails demande" widgetVar="d2" modal="true"
id="d2" dynamic="true" showEffect="fade" hideEffect="fade"
resizable="true" position="center">
<p:outputPanel id="p2" style="text-align:center;">
<p:dataTable
value="#{demandeBean.demandeSelectionnee.detailDemandes}" var="d">
<p:column headerText="Acte">
<h:outputText value="#{d.acteMedical.typeActe}" />
</p:column>
<p:column headerText="Montant">
<h:outputText value="#{d.montant}" />
</p:column>
<p:column headerText="Date">
<h:outputText value="#{d.dateActe}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</p:column>
<p:column style="text-align: center" headerText="images"
width="10%">
<p:commandButton update="#form" oncomplete="PF('diag').show()"
rendered="#{not empty a.images}" icon="ui-icon-search"
title="View">
<f:setPropertyActionListener value="#{a}"
target="#{demandeBean.demandeSelectionnee}" />
</p:commandButton>
</p:column>
</p:dataTable>
</p:outputPanel>
</p:dialog>
<p:dialog header="Détails demande" widgetVar="d3" modal="true"
id="d3" dynamic="true" showEffect="fade" hideEffect="fade"
resizable="true" position="center">
<p:outputPanel id="p3" style="text-align:center;">
<p:dataTable
value="#{demandeBean.demandeSelectionnee.detailDemandes}" var="d">
<p:column headerText="Acte">
<h:outputText value="#{d.acteMedical.typeActe}" />
</p:column>
<p:column headerText="Montant">
<h:outputText value="#{d.montant}" />
</p:column>
<p:column headerText="Date">
<h:outputText value="#{d.dateActe}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</p:column>
<p:column style="text-align: center" headerText="images"
width="10%">
<p:commandButton update="#form" oncomplete="PF('diag').show()"
rendered="#{not empty a.images}" icon="ui-icon-search"
title="View">
<f:setPropertyActionListener value="#{a}"
target="#{demandeBean.demandeSelectionnee}" />
</p:commandButton>
</p:column>
</p:dataTable>
</p:outputPanel>
</p:dialog>
<p:dialog header="Détails demande" widgetVar="d4" modal="true"
id="d4" dynamic="true" showEffect="fade" hideEffect="fade"
resizable="true" position="center">
<p:outputPanel id="p4" style="text-align:center;">
<p:dataTable
value="#{demandeBean.demandeSelectionnee.detailDemandes}" var="d">
<p:column headerText="Acte">
<h:outputText value="#{d.acteMedical.typeActe}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</p:dialog>
<p:dialog header="images" widgetVar="diag" modal="true"
showEffect="fade" hideEffect="fade" resizable="true"
position="center" height="500" width="650">
<p:outputPanel id="gal" style="text-align:center;">
<p:galleria value="#{demandeBean.demandeSelectionnee.images}"
showFilmstrip="true" autoPlay="false" var="image">
<p:graphicImage
value="http://localhost:18080/openCars/images/#{image}"
alt="Image Description for #{image}" title="#{image}" />
</p:galleria>
</p:outputPanel>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
java Bean:
package mBeans;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import persistence.ActeMedical;
import persistence.Assure;
import persistence.Demande;
import persistence.DetailDemande;
import persistence.EtatDemande;
import persistence.User;
import services.DemandeServicesLocal;
import services.UserServicesLocal;
#ManagedBean
#ViewScoped
public class DemandeBean {
private List<String> images = new ArrayList<>();
private String matriculeForAdminToAdd;
private List<DetailDemande> detailDemandesTMP = new ArrayList<>();
private ActeMedical acteMedical = new ActeMedical();
private List<ActeMedical> acteMedicalsToAdd = new ArrayList<>();
private Integer idOf;
private List<Demande> allDemandes = new ArrayList<>();
private List<Demande> allDemandesParAssures = new ArrayList<>();
private List<Demande> allDemandesParEmployer = new ArrayList<>();
private Demande demande = new Demande();
private Demande demandeSelectionnee = new Demande();
private List<String> etats = new ArrayList<>();
private String etatChoisi = "";
private Date dateActe;
private Double montant;
private ActeMedical acteMedicalSelection = new ActeMedical();
private List<ActeMedical> acteMedicals = new ArrayList<>();
private List<Assure> assuresParEmployee = new ArrayList<>();
#EJB
private DemandeServicesLocal demandeServicesLocal;
#EJB
private UserServicesLocal userServicesLocal;
#ManagedProperty(value = "#{identity}")
private Identity identity;
#PostConstruct
public void init() {
etats.add("ENCOURS");
etats.add("ACCEPTE");
etats.add("AMODIFIER");
}
public List<String> completeTheme(String query) {
List<User> users = userServicesLocal.findAllUsers();
List<String> list = new ArrayList<>();
for (User u : users) {
list.add(u.getMatricule());
}
return list;
}
public void addDetailToList() {
DetailDemande detailDemande = new DetailDemande(dateActe, demande, acteMedical, montant);
detailDemandesTMP.add(detailDemande);
detailDemande = new DetailDemande();
vider();
}
public void deleteDetailToList(DetailDemande detailDemande) {
detailDemandesTMP.remove(detailDemande);
detailDemande = new DetailDemande();
vider();
}
public String doAddDemande() {
demande.setImages(images);
demande.setEmployer(demandeServicesLocal.findUserById(idOf));
if (!detailDemandesTMP.isEmpty()) {
Demande d = demandeServicesLocal.addDemande(demande);
for (DetailDemande t : detailDemandesTMP) {
demandeServicesLocal.ajouterDetailDemande(t.getDateActe(), d, t.getActeMedical(), t.getMontant());
}
demande = new Demande();
dateActe = null;
montant = null;
detailDemandesTMP = new ArrayList<>();
return "/pages/listDemandesByEmployer?faces-redirect=true";
} else {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Veuillez ajouter un acte médical", "");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "";
}
}
public String doAddDemandeBtAdmin() {
demande.setImages(images);
demande.setEmployer(demandeServicesLocal.findUserByMatricule(matriculeForAdminToAdd));
if (!detailDemandesTMP.isEmpty()) {
Demande d = demandeServicesLocal.addDemande(demande);
for (DetailDemande t : detailDemandesTMP) {
demandeServicesLocal.ajouterDetailDemande(t.getDateActe(), d, t.getActeMedical(), t.getMontant());
}
demande = new Demande();
dateActe = null;
montant = null;
detailDemandesTMP = new ArrayList<>();
matriculeForAdminToAdd = null;
return "/pages/listDemandes?faces-redirect=true";
} else {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Veuillez ajouter un acte médical", "");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "";
}
}
public void doSome() {
System.out.println(idOf);
}
public void vider() {
dateActe = null;
montant = 0D;
}
public void doCreateDetail() {
demandeServicesLocal.ajouterDetailDemande(dateActe, demande, acteMedicalSelection, montant);
}
public List<Demande> getAllDemandes() {
allDemandes = demandeServicesLocal.findAllDemandes();
return allDemandes;
}
public void traiterDemande() {
if (etatChoisi.equals("ACCEPTE")) {
demandeServicesLocal.addDemande(demandeSelectionnee);
} else if (etatChoisi.equals("AMODIFIER")) {
demandeSelectionnee.setEtatDemande(EtatDemande.AMODIFIER);
demandeServicesLocal.addDemande(demandeSelectionnee);
}
}
public int hatImagesSize() {
System.out.println(images.size());
return images.size();
}
public void setAllDemandes(List<Demande> allDemandes) {
this.allDemandes = allDemandes;
}
public Demande getDemande() {
return demande;
}
public void setDemande(Demande demande) {
this.demande = demande;
}
public List<Demande> getAllDemandesParEmployer() {
allDemandesParEmployer = demandeServicesLocal.findAllDemandesParEmployer(identity.getUser());
return allDemandesParEmployer;
}
public void setAllDemandesParEmployer(List<Demande> allDemandesParEmployer) {
this.allDemandesParEmployer = allDemandesParEmployer;
}
public DemandeServicesLocal getDemandeServicesLocal() {
return demandeServicesLocal;
}
public void setDemandeServicesLocal(DemandeServicesLocal demandeServicesLocal) {
this.demandeServicesLocal = demandeServicesLocal;
}
public Identity getIdentity() {
return identity;
}
public void setIdentity(Identity identity) {
this.identity = identity;
}
public void onRowSelect(SelectEvent event) {
demandeSelectionnee = (Demande) event.getObject();
FacesMessage msg = new FacesMessage("Car Selected", ((Demande) event.getObject()).getEtatDemande().toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected",
((Demande) event.getObject()).getEtatDemande().toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public Demande getDemandeSelectionnee() {
return demandeSelectionnee;
}
public void setDemandeSelectionnee(Demande demandeSelectionnee) {
this.demandeSelectionnee = demandeSelectionnee;
}
public List<String> getEtats() {
return etats;
}
public void setEtats(List<String> etats) {
this.etats = etats;
}
public String getEtatChoisi() {
return etatChoisi;
}
public void setEtatChoisi(String etatChoisi) {
this.etatChoisi = etatChoisi;
}
public Date getDateActe() {
dateActe = new Date();
return dateActe;
}
public void setDateActe(Date dateActe) {
this.dateActe = dateActe;
}
public Double getMontant() {
return montant;
}
public void setMontant(Double montant) {
this.montant = montant;
}
public ActeMedical getActeMedicalSelection() {
return acteMedicalSelection;
}
public void setActeMedicalSelection(ActeMedical acteMedicalSelection) {
this.acteMedicalSelection = acteMedicalSelection;
}
public List<ActeMedical> getActeMedicals() {
acteMedicals = demandeServicesLocal.findAllActe();
return acteMedicals;
}
public void setActeMedicals(List<ActeMedical> acteMedicals) {
this.acteMedicals = acteMedicals;
}
public List<Assure> getAssuresParEmployee() {
assuresParEmployee = demandeServicesLocal.findAssuresByEmployee(identity.getUser());
return assuresParEmployee;
}
public void setAssuresParEmployee(List<Assure> assuresParEmployee) {
this.assuresParEmployee = assuresParEmployee;
}
public Integer getIdOf() {
return idOf;
}
public void setIdOf(Integer idOf) {
this.idOf = idOf;
}
public List<Demande> getAllDemandesParAssures() {
allDemandesParAssures = demandeServicesLocal.findAllDemandesParAssureDeEmployer(identity.getUser());
return allDemandesParAssures;
}
public void setAllDemandesParAssures(List<Demande> allDemandesParAssures) {
this.allDemandesParAssures = allDemandesParAssures;
}
public ActeMedical getActeMedical() {
return acteMedical;
}
public void setActeMedical(ActeMedical acteMedical) {
this.acteMedical = acteMedical;
}
public List<ActeMedical> getActeMedicalsToAdd() {
return acteMedicalsToAdd;
}
public void setActeMedicalsToAdd(List<ActeMedical> acteMedicalsToAdd) {
this.acteMedicalsToAdd = acteMedicalsToAdd;
}
public List<DetailDemande> getDetailDemandesTMP() {
return detailDemandesTMP;
}
public void setDetailDemandesTMP(List<DetailDemande> detailDemandesTMP) {
this.detailDemandesTMP = detailDemandesTMP;
}
public String getMatriculeForAdminToAdd() {
return matriculeForAdminToAdd;
}
public void setMatriculeForAdminToAdd(String matriculeForAdminToAdd) {
this.matriculeForAdminToAdd = matriculeForAdminToAdd;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
demandeSelectionnee = demandeServicesLocal.findDemandeById(Integer.valueOf(event.getRowKey()));
if (newValue != null && !newValue.equals(oldValue)) {
if (newValue.equals("ENCOURS")) {
demandeSelectionnee.setEtatDemande(EtatDemande.ENCOURS);
demandeServicesLocal.addDemande(demandeSelectionnee);
} else if (newValue.equals("AMODIFIER")) {
demandeSelectionnee.setEtatDemande(EtatDemande.AMODIFIER);
demandeServicesLocal.addDemande(demandeSelectionnee);
} else if (newValue.equals("ACCEPTE")) {
demandeSelectionnee.setEtatDemande(EtatDemande.TRANSMISE);
demandeServicesLocal.addDemande(demandeSelectionnee);
}
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cell Changed",
"Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
If I was understand right your problem, first of all I think your button must have oncomplete="PF('d3').show();" instead of onclick="PF('d3').show();"
and it must have attribute update="d3" where d3 to be the right dialog widget ID.
Let's explain how it works: first click the button - which updates the property in javaBean, after that it will update the dialog with the new changes from the back-end. Finally, after the request ends, it will open the dialog.

Use List for source in datatable with lazyLoading

I have the list with very data. I want to show data in Primeface data table with lazy loading ability. now I show data normal in data Table, but it is slow.
How can use lazy loading ability?
XHTML File :
<ui:composition template="template.xhtml">
<ui:define name="content">
<p:panel id="pnlLogInformationPage">
<h:form id="logInformation">
<div class="contentContainer-full-left">
<p:dataTable var="log" value="#{logInformationMB.logInformationList}" id="logTable"
width="100%" liveResize="true">
<p:column headerText="ID" sortBy="Id">
<h:outputText value="#{logInformation.Id}" />
</p:column>
<p:column headerText="Name" sortBy="Name">
<h:outputText value="#{logInformation.Name}" />
</p:column>
</p:dataTable>
</div>
</h:form>
</p:panel>
</ui:define>
ManageBean File:
#ManagedBean(name = "logInformationMB")
#ViewScoped
public class LogManagedBean implements Serializable {
#PostConstruct
public void initComponents() {
loadLogInformation();
}
public List<LogInformationDTO> getLogInformationList() {
return logInformationList;
}
public void setLogInformationList(final List<LogInformationDTO> pLogInformationList) {
logInformationList = pLogInformationList;
}
public void loadLoagInformation(final ComponentSystemEvent event) {
setLogLInformationlist(getLogInformationList();
}
public void loadInformationProtokolle() {
loadInformationProtokolle(null);
}
public List<LogInformationDTO> getLogInformation() {
final List<LogInformationDTO> lcResult = new ArrayList<LogInformationDTO>();
....
return lcResult;
}
}
According to your code, you didn't use lazyloading. you just get all your datas.
It will be slow when your data is too big.
See my steps below:
1- Instead of using #{logInformationMB.logInformationList}, you need to create new class which extend LazyDataModel class and create a service that can get data page by page.
public class LogInformationDataModel extends LazyDataModel<LogInformationDTO> {
private List<LogInformationDTO> logInformationList;
private LogInformationService logInformationService = new LogInformationService();
#Override
public List<LogInformationDTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
// TODO implement sort
setRowCount(logInformationService.count(filters));
logInformationList = logInformationService.list(first / pageSize, pageSize, sortField, sort, filters);
return logInformationList;
}
#Override
public LogInformationDTO getRowData(String rowKey) {
for(LogInformationDTO logInformation : logInformationList) {
if(logInformation.getId().equals(rowKey))
return logInformation;
}
return null;
}
#Override
public Object getRowKey(LogInformationDTO logInformation) {
return logInformation.getId();
}
}
2- Register data model in your Manage bean
#ManagedBean(name = "logInformationMB")
#ViewScoped
public class LogManagedBean implements Serializable {
private LogInformationDataModel dataModel = new LogInformationDataModel();
public LogInformationDataModel getDataModel() {
return dataModel;
}
}
3- Add lazy attribe (lazy="true") to your p:dataTable and using pagination
<p:dataTable var="log" value="#{logInformationMB.dataModel}" var="logInformation" id="logTable"
width="100%"
lazy="true"
paginator="true"
paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,50,100"
>
<p:column headerText="ID" sortBy="Id">
<h:outputText value="#{logInformation.Id}" />
</p:column>
<p:column headerText="Name" sortBy="Name">
<h:outputText value="#{logInformation.Name}" />
</p:column>
</p:dataTable>
I Hope my answer could solve your issue.
Below is the link you can check :
Primefaces lazydatamodel

compositeComponent with primefaces datatable selection does not return object

I've made a composite component using primefaces 5.1. I want a dialog to show up, you can input a name and search the db. Then you can select one entry and the dialog closes again. My Problem ist that the selection in the dataTable always returns null...
this is the composite:
<html xmlns="http://www.w3.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:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j" xmlns:p="http://primefaces.org/ui"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface componentType="searchCustomer">
<composite:attribute name="customerCache" required="true"
type="com.hji.tis.ui.cache.customer.CustomerCache" />
<composite:attribute name="useExtendedCustomersOnly" default="false" />
</composite:interface>
<composite:implementation>
<p:commandLink styleClass="ui-icon ui-icon-search"
id="searchCustomerIcon" onclick="PF('searchCustomerDialog').show();" />
<p:tooltip for="searchCustomerIcon"
value="#{msgs['request.searchByCustomerNumber']}" />
<p:dialog header="#{msgs['general.searchCustomer']}" resizable="false"
draggable="false" width="500" height="450" modal="true"
appendTo="#(body)" widgetVar="searchCustomerDialog">
<p:panel id="searchCustomerDialogContent" style="width:100%">
<p:panelGrid style="width:480px">
<p:row>
<p:column style="width:60px">
<p:graphicImage value="/resources/images/userSearch.png"
width="50" height="50" />
</p:column>
<p:column style="width:100px">
<p:outputLabel value="#{msgs['general.customerName']}" />
</p:column>
<p:column style="width:160px">
<p:inputText value="#{cc.custSearch_name}"
id="input_searchCustomerName" />
</p:column>
<p:column>
<p:commandLink styleClass="ui-icon ui-icon-search"
action="#{cc.findCustomersByName}"
update="searchCustomerDialogContent"
process="#this, input_searchCustomerName" partialSubmit="true" />
</p:column>
</p:row>
<p:row>
<p:column colspan="4">
<p:dataTable value="#{cc.filteredCustomers}" var="customer"
scrollable="true" scrollHeight="300"
emptyMessage="#{msgs['general.noSelection']}"
selection="#{cc.selectedCustomer}" rowKey="#{customer.id}"
selectionMode="single">
<p:ajax event="rowSelect" process="#this" />
<p:column headerText="#{msgs['general.customerName']}"
styleClass="unmarkable">
<h:outputText value="#{customer.fullName}"
rendered="#{!customer.extendedCustomer}" />
<h:outputText value="#{customer.name}"
rendered="#{customer.extendedCustomer}" />
</p:column>
<p:column headerText="#{msgs['general.address']}"
styleClass="unmarkable">
<h:outputText
value="#{customer.homeAddress.address.country}, #{customer.homeAddress.address.zipCode} #{customer.homeAddress.address.city}, #{customer.homeAddress.address.street} #{customer.homeAddress.address.houseNr}" />
</p:column>
</p:dataTable>
</p:column>
</p:row>
<p:row>
<p:column colspan="4">
<p:commandButton icon="ui-icon-check" style="float:right"
action="#{cc.test}" process="#this, searchCustomerDialogContent"
partialSubmit="true" />
</p:column>
</p:row>
</p:panelGrid>
</p:panel>
</p:dialog>
</composite:implementation>
</html>
and this is the Faces Component:
package com.hji.tis.ui.util.customComponents;
import java.io.IOException;
import java.util.List;
import javax.faces.component.FacesComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.event.SelectEvent;
import com.hji.tis.domain.model.customer.Customer;
import com.hji.tis.ui.cache.customer.CustomerCache;
/**
* NamingContainer for the custom element searchCustomer.
*
* #author mayra
*
*/
#FacesComponent("searchCustomer")
public class SearchCustomer extends UINamingContainer {
private final String CUSTOMER_CACHE = "customerCache";
private final String USER_EXTENDED_CUSTOMERS_ONLY = "useExtendedCustomersOnly";
private final String FILTERED_CUSTOMERS = "filteredCustomers";
private final String SELECTED_CUSTOMER = "selectedCustomer";
#Getter
#Setter
private String custSearch_name;
#Getter
#Setter
private Customer custSearch_selectedCustomer;
#Override
public void encodeBegin(FacesContext facesContext) throws IOException {
initCustomerCache();
initUseExtendedCustomersOnly();
super.encodeBegin(facesContext);
}
public void onRowSelect(SelectEvent event) {
System.out.println(((Customer) (event.getObject())).getFullName());
}
/**
* finds the customer by the name set to the _Name field. Decides wether
* only private Customers should be returned or extended.
*/
public void findCustomersByName() {
this.custSearch_selectedCustomer = null;
if (useExtendedCustomersOnly()) {
setFilteredCustomers(getCustomerCache().findExtendedCustomerEntriesByName(custSearch_name));
} else {
setFilteredCustomers(getCustomerCache().findAllCustomerEntriesByName(custSearch_name));
}
}
private boolean useExtendedCustomersOnly() {
return getStateHelperValue(USER_EXTENDED_CUSTOMERS_ONLY);
}
private CustomerCache getCustomerCache() {
return getStateHelperValue(CUSTOMER_CACHE);
}
public Customer getSelectedCustomer() {
return (Customer) this.getStateHelper().get(SELECTED_CUSTOMER);
}
public void setSelectedCustomer(Customer customer) {
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!HERE THE CUSTOMER IS ALWAYS NULL
this.getStateHelper().put(SELECTED_CUSTOMER, customer);
}
public List<Customer> getFilteredCustomers() {
return (List<Customer>) this.getStateHelper().get(FILTERED_CUSTOMERS);
}
private void setFilteredCustomers(List<Customer> customers) {
this.getStateHelper().put(FILTERED_CUSTOMERS, customers);
}
/**
* stores the customerCache in the state helper.
*/
private void initCustomerCache() {
CustomerCache customerCache = getAttributeValue(CUSTOMER_CACHE);
this.getStateHelper().put(CUSTOMER_CACHE, customerCache);
}
private void initUseExtendedCustomersOnly() {
String value = getAttributeValue(USER_EXTENDED_CUSTOMERS_ONLY);
boolean boolValue = false;
if (value.equalsIgnoreCase("TRUE")) {
boolValue = true;
} else {
boolValue = false;
}
this.getStateHelper().put(USER_EXTENDED_CUSTOMERS_ONLY, boolValue);
}
/**
* Return specified attribute value or otherwise the specified default if
* it's null.
*/
#SuppressWarnings("unchecked")
private <T> T getAttributeValue(String key) {
return (T) this.getAttributes().get(key);
}
#SuppressWarnings("unchecked")
private <T> T getStateHelperValue(String key) {
return (T) this.getStateHelper().get(key);
}
}
Maybe someone knows the reason why?
Thanks!

Displaying and editing Set values in PrimeFaces

I have JSF 2.2, PrimeFaces 3.5, Spring 3.1.3, Hibernate 4.1, MySQL web app.
On home.xhtml I have a tabview with 3 nested dataTables for 3 entities (Users, Computers, Applications) and CRUD buttons (see screenshot). Every button calls a dialog window with a form to add/edit/delete entity.
I will provide all code that is somehow associated with a problem (you may not need to check them all, I just made sure that every part of code you may be interested in is present below.)
Please, consider the following script for creating entities and their corresponding classes:
CREATE TABLE computers (
computer_id INT AUTO_INCREMENT,
computer_name VARCHAR(15) NOT NULL,
ip_address VARCHAR(15) NOT NULL UNIQUE,
login VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY(computer_id)
) ENGINE=InnoDB;
CREATE TABLE applications (
app_id INT AUTO_INCREMENT,
app_name VARCHAR(255) NOT NULL,
vendor_name VARCHAR(255) NOT NULL,
license_required TINYINT(1) NOT NULL,
PRIMARY KEY(app_id)
) ENGINE=InnoDB;
CREATE TABLE computer_app (
computer_id INT,
app_id INT,
FOREIGN KEY (computer_id)
REFERENCES computers(computer_id)
ON DELETE CASCADE,
FOREIGN KEY (app_id)
REFERENCES applications(app_id)
ON DELETE CASCADE
) ENGINE = InnoDB;
Computer.class:
#Entity
#Table(name="computers", catalog="adminportal")
public class Computer implements Serializable {
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="computer_id", unique=true, nullable=false)
private Integer computerId;
#Column(name="computer_name", nullable=false, length=15)
private String computerName;
#Column(name="ip_address", unique=true, nullable=false, length=15)
private String ipAddress;
#Column(name="login", nullable=false, length=20)
private String login;
#Column(name="password", nullable=false, length=20)
private String password;
#OneToMany(fetch=FetchType.EAGER, mappedBy="computers")
private Set<ComputerApp> computerApps = new HashSet<>(0);
Application.java:
#Entity
#Table(name="applications", catalog="adminportal")
public class Application implements Serializable {
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="app_id", unique=true, nullable=false)
private Integer appId;
#Column(name="app_name", nullable=false)
private String appName;
#Column(name="vendor_name", nullable=false)
private String vendorName;
#Column(name="license_required", nullable=false, columnDefinition = "BIT", length = 1)
private boolean licenseRequired;
#OneToMany(fetch=FetchType.LAZY, mappedBy="applications")
private Set<ComputerApp> computerApps = new HashSet<>(0);
ComputerApp.java
#Entity
#Table(name="computer_app" ,catalog="adminportal")
public class ComputerApp implements Serializable {
#EmbeddedId
#AttributeOverrides( {
#AttributeOverride(name="computerId", column=#Column(name="computer_id") ),
#AttributeOverride(name="appId", column=#Column(name="app_id") ) } )
private ComputerAppId id;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="app_id", insertable=false, updatable=false)
private Application applications;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="computer_id", insertable=false, updatable=false)
private Computer computers;
ComputerAppId.java:
#Embeddable
public class ComputerAppId implements Serializable {
#Column(name = "computer_id")
private Integer computerId;
#Column(name = "app_id")
private Integer appId;
home.xhtml:
<p:tabView id="tab" orientation="left">
<p:tab title="Users" rendered="#{request.isUserInRole('ROLE_ADMIN')}">
<h:form id="form1">
<h:panelGrid columns="9" >
<p:commandButton type="button" value="Add" onclick="dlg1.show()" />
<p:commandButton id="editUser" type="button" value="Edit" onclick="dlg2.show()" disabled="#{homeBean.selectedUser == null}"/>
<p:commandButton id="deleteUser" type="button" onclick="confirmation1.show()" value="Delete" disabled="#{homeBean.selectedUser == null}"/>
<p:confirmDialog id="delete1" header="Confirmation" widgetVar="confirmation1" >
<p:commandButton value="Yes" update=":tab:users" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation1.hide()" action="#{homeBean.deleteUser}" />
<p:commandButton value="No" onclick="confirmation1.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
<f:facet name="message">
<p:outputPanel>
<h:outputFormat value="#{homeBean.deleteUserMsg}"/>
</p:outputPanel>
</f:facet>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="users" var="user" value="#{homeBean.users}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedUser}" rowKey="#{user.userId}"
sortMode="single">
<p:ajax event="rowSelect" listener="#{homeBean.onUserRowSelect}" update=":tab:form1:deleteUser, :tab:form1:editUser, :tab:form1:delete1, :dlg2form:panel2"/>
<p:column headerText="Login" sortBy="#{user.login}">
<h:outputText value="#{user.login}"/>
</p:column>
<p:column headerText="Password" sortBy="#{user.password}">
<h:outputText value="#{user.password}"/>
</p:column>
<p:column headerText="Role" sortBy="#{user.role}">
<h:outputText value="#{user.role}"/>
</p:column>
<p:column headerText="Name" sortBy="#{user.firstName}">
<h:outputText value="#{user.firstName}"/>
</p:column>
<p:column headerText="Surname" sortBy="#{user.lastName}">
<h:outputText value="#{user.lastName}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:users" fileName="Users"/>
</p:tab>
<p:tab title="Computers">
<h:form id="form2">
<h:panelGrid columns="9" rendered="#{request.isUserInRole('ROLE_ADMIN')}">
<p:commandButton type="button" value="Add" onclick="dlg3.show()"/>
<p:commandButton id="editComp" type="button" value="Edit" onclick="dlg4.show()" disabled="#{homeBean.selectedComputer == null}"/>
<p:commandButton id="deleteComp" type="button" onclick="confirmation2.show()" value="Delete" disabled="#{homeBean.selectedComputer == null}"/>
<p:confirmDialog id="delete2" header="Confirmation"
severity="alert" widgetVar="confirmation2">
<p:commandButton value="Yes" update=":tab:computers" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation2.hide()" action="#{homeBean.deleteComputer}"/>
<p:commandButton value="No" onclick="confirmation2.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
<f:facet name="message">
<p:outputPanel>
<h:outputFormat value="#{homeBean.deleteCompMsg}"/>
</p:outputPanel>
</f:facet>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="computers" var="computer" value="#{homeBean.computers}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedComputer}" rowKey="#{computer.computerId}"
sortMode="single" >
<p:ajax event="rowSelect" listener="#{homeBean.onCompRowSelect}" update=":tab:form2:editComp, :tab:form2:deleteComp, :tab:form2:delete2, :dlg4form:panel4"/>
<p:column headerText="Login" sortBy="#{computer.login}">
<h:outputText value="#{computer.login}"/>
</p:column>
<p:column headerText="Password" sortBy="#{computer.password}">
<h:outputText value="#{computer.password}"/>
</p:column>
<p:column headerText="Name" sortBy="#{computer.computerName}" >
<h:outputText value="#{computer.computerName}"/>
</p:column>
<p:column headerText="IP address" sortBy="#{computer.ipAddress}">
<h:outputText value="#{computer.ipAddress}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:computers" fileName="Computers"/>
</p:tab>
<p:tab title="Applications">
<h:form id="form3" rendered="#{request.isUserInRole('ROLE_ADMIN')}">
<h:panelGrid columns="9">
<p:commandButton type="button" value="Add" onclick="dlg5.show()"/>
<p:commandButton id="editApp" type="button" value="Edit" onclick="dlg6.show()" disabled="#{homeBean.selectedApplication == null}"/>
<p:commandButton id="deleteApp" type="button" onclick="confirmation3.show()" value="Delete" disabled="#{homeBean.selectedApplication == null}"/>
<p:confirmDialog id="delete3" message="Are you sure you want to delete this application?" header="Confirmation"
severity="alert" widgetVar="confirmation3">
<p:commandButton value="Yes" update=":tab:applications" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation3.hide()" action="#{homeBean.deleteApplication}"/>
<p:commandButton value="No" onclick="confirmation3.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
<f:facet name="message">
<p:outputPanel>
<h:outputFormat value="#{homeBean.deleteAppMsg}"/>
</p:outputPanel>
</f:facet>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="applications" var="app" value="#{homeBean.applications}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedApplication}" rowKey="#{app.appId}"
sortMode="single" >
<p:ajax event="rowSelect" listener="#{homeBean.onAppRowSelect}" update=":tab:form3:editApp, :tab:form3:deleteApp, :tab:form3:delete3, :dlg6form:panel6"/>
<p:column headerText="Name" sortBy="#{app.appName}">
<h:outputText value="#{app.appName}"/>
</p:column>
<p:column headerText="Vendor" sortBy="#{app.vendorName}" >
<h:outputText value="#{app.vendorName}"/>
</p:column>
<p:column headerText="License required" sortBy="#{app.licenseRequired}">
<h:outputText value="#{app.licenseRequired}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:applications" fileName="Applications" />
</p:tab>
</p:tabView>
<!--DIALOGS ARE NOT PRESENT SINCE POST IS TOO LONG-->
</h:body>
</ui:component>
HomeBean.java:
#Component
#Scope("session")
public class HomeBean extends BaseBean {
private static final String editUserBtn = "tab:form1:editUser";
private static final String deleteUserBtn = "tab:form1:deleteUser";
private static final String editCompBtn = "tab:form2:editComp";
private static final String deleteCompBtn = "tab:form2:deleteComp";
private static final String editAppBtn = "tab:form3:editApp";
private static final String deleteAppBtn = "tab:form3:deleteApp";
private List<User> users;
private List<Computer> computers;
private List<Application> applications;
private User selectedUser, newUser;
private Computer selectedComputer, newComputer;
private Application selectedApplication, newApplication;
private String deleteUserMsg, deleteCompMsg, deleteAppMsg;
private RequestContext rc;
#PostConstruct
public void init() {
setUsers(hibernateDBManager.getAllUsers());
setComputers(hibernateDBManager.getAllComputers());
setApplications(hibernateDBManager.getAllApplications());
newUser = new User();
newComputer = new Computer();
newApplication = new Application();
rc = RequestContext.getCurrentInstance();
}
public void addUser() throws NoSuchAlgorithmException {
if (hibernateDBManager.insertUser(newUser)) {
users.add(newUser);
newUser = new User();
updateUserButtons();
}
}
public void editUser() throws NoSuchAlgorithmException {
if (hibernateDBManager.updateUser(selectedUser)) {
users.set(users.indexOf(selectedUser), selectedUser);
selectedUser = null;
updateUserButtons();
}
}
public void deleteUser() throws IOException {
if (selectedUser != null) {
if (hibernateDBManager.deleteUserById(selectedUser.getUserId()) > 0) {
users.remove(selectedUser);
selectedUser = null;
updateUserButtons();
}
}
}
public void addComputer() {
if (newComputer != null && hibernateDBManager.insertComputer(newComputer)) {
computers.add(newComputer);
newComputer = new Computer();
updateCompButtons();
}
}
public void editComputer() {
if (hibernateDBManager.updateComputer(selectedComputer)) {
computers.set(computers.indexOf(selectedComputer), selectedComputer);
selectedComputer = null;
updateCompButtons();
}
}
public void deleteComputer() {
if (selectedComputer != null) {
if (hibernateDBManager.deleteComputerById(selectedComputer.getComputerId()) > 0) {
computers.remove(selectedComputer);
selectedComputer = null;
updateCompButtons();
}
}
}
public void addApplication() {
if (newApplication != null && hibernateDBManager.insertApplication(newApplication)) {
applications.add(newApplication);
newApplication = new Application();
updateAppButtons();
}
}
public void editApplication() {
if (hibernateDBManager.updateApplication(selectedApplication)) {
applications.set(applications.indexOf(selectedApplication), selectedApplication);
selectedApplication = null;
updateAppButtons();
}
}
public void deleteApplication() {
if (selectedApplication != null) {
if (hibernateDBManager.deleteApplicationById(selectedApplication.getAppId()) > 0) {
applications.remove(selectedApplication);
selectedApplication = null;
updateAppButtons();
}
}
}
public void onUserRowSelect(SelectEvent event) {
setSelectedUser((User) event.getObject());
setDeleteUserMsg("Are you sure you want to delete user "
+ selectedUser.getFirstName() + " " + selectedUser.getLastName() + "?");
}
public void onCompRowSelect(SelectEvent event) {
setSelectedComputer((Computer) event.getObject());
deleteCompMsg = "Are you sure you want to delete computer "
+ selectedComputer.getComputerName()
+ " (" + selectedComputer.getIpAddress() + ") ?";
}
public void onAppRowSelect(SelectEvent event) {
setSelectedApplication((Application) event.getObject());
deleteAppMsg = "Are you sure you want to delete application "
+ selectedApplication.getAppName() + "?";
}
protected void updateUserButtons() {
rc.update(editUserBtn);
rc.update(deleteUserBtn);
}
protected void updateCompButtons() {
rc.update(editCompBtn);
rc.update(deleteCompBtn);
}
protected void updateAppButtons() {
rc.update(editAppBtn);
rc.update(deleteAppBtn);
}
//Getters/setters
}
My target is to find the best way to display Set values (Set in Computer) in a dataTable or somehow else manage adding and removing applications from/to selected computers.
Every answer is highly appreciated and responded quickly!
Thank you.
In the end I used PrimeFaces's <picklist> element as a best approach in my issue.

Primefaces datatable, not updated after delete a row

I'm trying deleting a row from my primefaces datatable but it never updates itself until I refresh the browser.
This is how I'm doing it:
<p:column headerText="Eliminar Usuario" rendered="#{user.current.tipo.equalsIgnoreCase('planta')}">
<p:commandButton action="#{usuarios.eliminar(o.idUsuario)}" value="Eliminar" update="#form"/>
</p:column>
I've tried wrapping the datatable into an h:panelgroup, I also tried using update=":formUsuarios:users" (the id of my form is formUsuarios and the id of the table is users). I put "ajax="true" in the commandButton, nothing has worked.
I don't know what else to try. I'm using primefaces 3.5.
Here is my bean:
#ManagedBean(name = "usuarios")
#ViewScoped
public class UsuariosBean {
#ManagedProperty(value="#{user}")
private LoginBean loginBean;
private List<UsuariosEntity> usuarios;
UsuariosEntity user=new UsuariosEntity();
private String nombre;
private int activo;
private String tipo;
private String password;
private String selection;
private UIComponent mybutton;
#PostConstruct
public void init(){
UsuariosEntity usuario=loginBean.getCurrent();
usuarios=new ArrayList<UsuariosEntity>();
if(usuario.getTipo().equalsIgnoreCase("Planta")){
usuarios= UsuariosDAO.getALL();
}else{
usuarios= UsuariosDAO.getALLbyRol(usuario.getUsuario());
}
}
public UIComponent getMybutton() {
return mybutton;
}
public void setMybutton(UIComponent mybutton) {
this.mybutton = mybutton;
}
public String getSelection() {
return selection;
}
public void setSelection(String selection) {
this.selection = selection;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getActivo() {
return activo;
}
public void setActivo(int activo) {
this.activo = activo;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public LoginBean getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
public UsuariosEntity getUser() {
return user;
}
public void setUser(UsuariosEntity user) {
this.user = user;
}
public List<UsuariosEntity> getUsuarios() {
return usuarios;
}
public void setUsuarios(List<UsuariosEntity> usuarios) {
this.usuarios = usuarios;
}
public void newUsuario(){
UsuariosEntity user=new UsuariosEntity();
user.setIdPlanta(2);
user.setActivo(this.activo);
user.setPassword(this.password);
user.setUsuario(this.nombre);
user.setTipo(this.selection);
List<UsuariosEntity>usuariox=UsuariosDAO.findbyname(this.nombre);
if (usuariox.size()==0){
UsuariosDAO.save(user);
}else{
FacesMessage message = new FacesMessage("El usuario ya existe en la base de datos");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(mybutton.getClientId(context), message);
}
}
public void eliminar(int id_user){
UsuariosEntity user=UsuariosDAO.find(id_user);
UsuariosDAO.eliminar(user);
}
public void onEdit(RowEditEvent event) {
UsuariosDAO.save(((UsuariosEntity)event.getObject()));
FacesMessage msg = new FacesMessage("Usuario Editado", ((UsuariosEntity) event.getObject()).getUsuario());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edición Cancelada", ((UsuariosEntity) event.getObject()).getUsuario());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
the view:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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"
template="/Contenido/Template.xhtml"
xmlns:p="http://primefaces.org/ui">
<ui:define name="page-content">
<h:form id="formUsuarios">
<p:growl id="messages" showDetail="true"/>
<p:dataTable id="users" value="#{usuarios.usuarios}" var="o" editable="true" scrollRows="20" scrollable="true" scrollHeight="150" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<f:facet name="header">Usuarios</f:facet>
<p:ajax event="rowEdit" listener="#{usuarios.onEdit}" update=":formUsuarios:messages" />
<p:ajax event="rowEditCancel" listener="#{usuarios.onCancel}" update=":formUsuarios:messages" />
<p:column headerText="#" style="width:6%">
<h:outputText value=" #{o.idUsuario} "/>
</p:column>
<p:column rendered="#{user.current.tipo.equalsIgnoreCase('planta')}" headerText="Nombre">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.usuario}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.usuario}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Nombre" rendered="#{user.current.tipo.equalsIgnoreCase('productor')||user.current.tipo.equalsIgnoreCase('exportadora')}">
<h:outputText value="#{o.usuario}" />
</p:column>
<p:column rendered="#{user.current.tipo.equalsIgnoreCase('planta')}" headerText="Estado" style="width:6%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.activo}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.activo}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Password">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="********" />
</f:facet>
<f:facet name="input">
<h:inputSecret value="#{o.password}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column rendered="#{user.current.tipo.equalsIgnoreCase('planta')}" headerText="Tipo">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.tipo}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.tipo}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Editar" style="width:6%">
<p:rowEditor />
</p:column>
<p:column headerText="Eliminar Usuario" rendered="#{user.current.tipo.equalsIgnoreCase('planta')}">
<p:commandButton actionListener="#{usuarios.eliminar(o.idUsuario)}" value="Eliminar" process="users" ajax="true"/>
</p:column>
</p:dataTable>
<br/>
</h:form>
<h:form>
<p:panelGrid id="grid" columns="3" rendered="#{user.current.tipo.equalsIgnoreCase('planta')}">
<f:facet name="header">
Crear Usuario
</f:facet>
<h:outputText value="Nombre"/>
<h:inputText id="nombre" label="name" value="#{usuarios.nombre}" required="true" requiredMessage="Debe ingresar un nombre"/>
<h:message for="nombre" style="color:red"/>
<h:outputText value="Contraseña" />
<h:inputText id="pass" label="pasw" value="#{usuarios.password}" required="true" requiredMessage="Debe ingresar una contraseña"/>
<h:message style="color:red" for="pass"/>
<h:outputText value="Tipo"/>
<h:selectOneMenu id="select1" value="#{usuarios.selection}" onchange="submit();" required="true" requiredMessage="Debe seleccionar un tipo de usuario">
<f:selectItem itemValue="Planta" itemLabel="Planta" />
<f:selectItem itemValue="Exportadora" itemLabel="Exportadora" />
<f:selectItem itemValue="Productor" itemLabel="Productor" />
</h:selectOneMenu>
<h:message style="color:red" for="select1"/>
<h:outputText value="Activo"/>
<h:selectOneMenu id="select2" value="#{usuarios.activo}" onchange="submit();" required="true" requiredMessage="Debe seleccionar una opción ">
<f:selectItem itemValue="0" itemLabel="Inactivo" />
<f:selectItem itemValue="1" itemLabel="Activo" />
</h:selectOneMenu>
<h:message style="color:red" for="select2" />
<f:facet name="footer">
<h:commandButton value="Crear" id="mybutton"
binding="#{usuarios.mybutton}"
class="button" action="#{usuarios.newUsuario}">
</h:commandButton>
<h:message style="color:red" for="mybutton" />
</f:facet>
</p:panelGrid>
</h:form>
</ui:define>
</ui:composition>
Changing the collection referred by the value doesn't immediately affect data table because the values that are shown are stored by the filtered collection.
1) If you specify the filteredValue attribute, you should manually clear that collection after the data table content has changed, for example after deleting the row. After update on the data table, it should refresh the content.
2) You can call filter() on the dataTable widget (client-side API). It always works but it generates additional AJAX request.