Action of CommandLink/CommandButton in p:treeTable is not invoked - primefaces

I download primefaces 3.1, add to my project tried to add a commandButton/commandLink into a column of a treeTable
but action of commandButton/commandLink in a column is not invoked except the root row.
What may the problem be? Thanks
EDIT:
treeTable in xhtml:
<p:treeTable var="catalog" value="#{catalogSelectBean.root}" lazy="true" selection="#{catalogSelectBean.selectedNode}" selectionMode="single">
<p:column>
<f:facet name="header">
<h:outputText value="Katalog Name" />
</f:facet>
<h:outputText value="#{catalog.name}" />
</p:column>
<p:column width="100">
<f:facet name="header">
<h:outputText value="Katalog Desc"/>
</f:facet>
<h:outputText value="#{catalog.description}"/>
</p:column>
<p:column>
<p:commandButton action="#{formProductRelationView.updateProductListForSelectedCatalog()}"
update=":main_form:selectProductTable"
value="Bring Products">
</p:commandButton>
</p:column>
</p:treeTable>
Bean:
#Component("catalogSelectBean")
#Scope("request")
public class CatalogSelectBean implements Serializable {
private static final long serialVersionUID = 1L;
#Autowired
private CatalogService catalogService;
private TreeNode root;
private TreeNode selectedNode;
private DualListModel<Catalog> pickListCatalogs;
public TreeNode getRoot() {
return root;
}
public TreeNode getSelectedNode() {
return selectedNode;
}
public void setSelectedNode(TreeNode selectedNode) {
this.selectedNode = selectedNode;
}
public void onNodeSelect(NodeSelectEvent event) {
Catalog g = (Catalog)event.getTreeNode().getData();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected", g.getName());
FacesContext.getCurrentInstance().addMessage(null, message);
}
public CatalogSelectBean() {
}
#PostConstruct
public void unLoad(){
createRoot();
createPickListModel();
}
private void createPickListModel() {
//Players
List<Catalog> source = catalogService.loadChilds(catalogService.getRootCatalog());
List<Catalog> target = new ArrayList<Catalog>();
pickListCatalogs = new DualListModel<Catalog>(source, target);
}
private void createRoot() {
Catalog g = null ;
g = catalogService.getRootCatalog();
root = new DefaultTreeNode("Root", null);
TreeNode caRoot = new DefaultTreeNode(g,root);
generateTree(caRoot,g);
}
private void generateTree(TreeNode subRoot, Catalog g) {
for(Catalog p : g.getChildCatalogs()){
TreeNode node0 = new DefaultTreeNode(p,subRoot);
if(p.getChildCatalogs()!= null && p.getChildCatalogs().size()>0)
generateTree(node0, p);
}
}
public void resetTree() {
root.setSelected(false);
}
public DualListModel<Catalog> getPickListCatalogs() {
return pickListCatalogs;
}
}
Also i have a formProductRelationView bean which has the updateProductListForSelectedCatalog() method.
Thanks for attention.

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.

How to keep selected row after dialog closes Primefaces

In Primefaces 5.2, Glassfish 4.0, I am developping a simple CRUD. I have 2 distinct issues related to row selection.
The user clicks on a row in the datatable, this row is highlighted, the user selects "Edit" menu in the contextual menu, a modal window is opened.
1/ When the user press "Cancel" button in the modal window, the dialog is correctly closed. But then if the user selects another row in the datatable, the values displayed in the new modal window corresponds to the first previous selection. How to update the selected values?
2/ When the user press "OK" button in the modal window, the dialog is correctly closed, the datatable is correctly updated. But the updated row in the datatable is not anymore highlighted, the user doesn't know which row has just been updated. Is there a way to keep highlighted the lastly updated row (but to reinitialize the selected values for futher selection) until next click on a row, and in parallel of other focused row?
searchCompany.xhtml code is:
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
<p:contextMenu for="table">
<p:menuitem value="View" update="detail" icon="ui-icon-search" oncomplete="PF('companyDialog').show()"/>
<p:menuitem value="Delete" update="table" icon="ui-icon-close" actionListener="#{dtContextMenuView.deleteCompany}"/>
</p:contextMenu>
<p:dataTable
id="table"
value="#{companyBean.allCompanies}"
var="company"
editable="true"
editmode="row"
widgetVar="cellCompanies"
sortBy="#{company.name}"
scrollable="true"
scrollWidth="1024"
scrollHeight="300"
rowKey="#{company.id}"
selection="#{companyBean.selectedCompany}"
selectionMode="single">
<!-- above: by default table is sorted by Company name -->
<!-- above: to freeze the 2 first columns : frozenColumns="2"-->
<p:column
style="width:150px"
sortBy="#{company.name}"
filterBy="#{company.name}"
filterMatchMode="contains">
<!-- Column is sortable -->
<f:facet name="header">
#{msg['name']} <!-- Title of the column -->
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{company.name}" />
</f:facet>
<f:facet name="input">
<h:inputText value="#{company.name}"/>
</f:facet>
</p:cellEditor>
</p:column>
(..)
</p:dataTable>
<p:dialog header="#{msg['detail']}" widgetVar="companyDialog" modal="true" showEffect="fade" resizable="false">
<p:panel id="detail" >
<p:panelGrid columns="2" rendered="#{not empty companyBean.selectedCompany}">
<h:outputText value="#{msg['name']}:" />
<p:inputText value="#{companyBean.selectedCompany.name}" />
<h:outputText value="#{msg['contact']}:" />
<p:inputText value="#{companyBean.selectedCompany.contact}" />
</p:panelGrid>
<p:commandButton action="#{companyBean.updateCompanyEnd}" value='#{msg.OK}' oncomplete="PF('companyDialog').hide();" update="table, :form:msgs"/>
<p:commandButton value='#{msg.cancel}' onclick="PF('companyDialog').hide();"/>
</p:panel>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
The bean code is :
package com.sdzee.bean;
#ManagedBean
#ViewScoped
public class CompanyBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final String CREATE_COMPANY = "createCompany";
private static final String DELETE_COMPANY = "deleteCompany";
private static final String UPDATE_COMPANY = "updateCompany";
private static final String LIST_ALL_COMPANIES = "searchCompany";
private static final String STAY_IN_THE_SAME_PAGE = null;
#EJB
private CompanyFacade companyFacade;
private Company company;
private List<Company> AllCompanies;
#PostConstruct
public void init() {
AllCompanies = companyFacade.findAll();
}
private Company selectedCompany;
public Company getCompany() {
if(company == null){
company = new Company();
}
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public List<Company> getAllCompanies() {
return AllCompanies;
}
public String updateCompanyEnd(){
try {
Company comp = selectedCompany;
companyFacade.update(comp);
} catch (EJBException e) {
FacesContext context = FacesContext.getCurrentInstance();
String texte = context.getApplication().evaluateExpressionGet(context, "#{msg['error']}", String.class);
sendErrorMessageToUser(texte+e);
return STAY_IN_THE_SAME_PAGE;
}
FacesContext context = FacesContext.getCurrentInstance();
String texte = context.getApplication().evaluateExpressionGet(context, "#{msg['update.successful']}", String.class);
FacesMessage message = new FacesMessage(texte, selectedCompany.getName());
FacesContext.getCurrentInstance().addMessage(null, message);
this.selectedCompany = company;
return LIST_ALL_COMPANIES;
}
public String deleteCompanyStart(){
return DELETE_COMPANY;
}
public String deleteCompanyEnd(){
try {
companyFacade.delete(company);
} catch (EJBException e) {
sendErrorMessageToUser("Error. Call the ADM");
return STAY_IN_THE_SAME_PAGE;
}
FacesContext context = FacesContext.getCurrentInstance();
String texte = context.getApplication().evaluateExpressionGet(context, "#{msg['delete.successful']}", String.class);
FacesMessage message = new FacesMessage(texte, company.getName());
FacesContext.getCurrentInstance().addMessage(null, message);
//sendInfoMessageToUser("Operation Complete: Delete");
return LIST_ALL_COMPANIES;
}
public String createCompanyStart(){
return CREATE_COMPANY;
}
public String createCompanyEnd(){
try {
companyFacade.save(company);
} catch (EJBException e) {
sendErrorMessageToUser("Error. Check if the weight is above 0 or call the adm");
return STAY_IN_THE_SAME_PAGE;
}
sendInfoMessageToUser("Operation Complete: Create");
return LIST_ALL_COMPANIES;
}
public String listAllCompanies(){
return LIST_ALL_COMPANIES;
}
private void sendInfoMessageToUser(String message){
FacesContext context = getContext();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
}
private void sendErrorMessageToUser(String message){
FacesContext context = getContext();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
}
private FacesContext getContext() {
FacesContext context = FacesContext.getCurrentInstance();
return context;
}
public Company getSelectedCompany() {
return selectedCompany;
}
public void setSelectedCompany(Company selectedCompany) {
this.selectedCompany = selectedCompany;
}
}

Prime faces 5.0: custom filter in data table ignored

I'm trying to have a selectonemenu as filter option in a data table
I've done several tests, with no success
Now I'm trying to create a sample custom filter, with selectOneButton, with static fields, trying to simplify, but again it doesn't work
<p:column filterBy="#{sController.getStatus(se)}" headerText="Stato"
style="text-align:center;" sortBy="#{sController.getStatus(se)}"
filterMatchMode="exact"
>
<f:facet name="filter">
<p:selectOneButton onchange="PF('sDataTableWV').filter()">
<f:converter converterId="javax.faces.Boolean" />
<f:selectItem itemLabel="All" itemValue="" />
<f:selectItem itemLabel="Sold" itemValue="true" />
<f:selectItem itemLabel="Sale" itemValue="false" />
</p:selectOneButton>
</f:facet>
<img src="#{resource[sController.getStatus(se)]}" />
</p:column>
The facet is completely ignored, I see the usual input field instead
-------------- EDIT ------------------
As per request, I prepared a new page taking the source code of the showcase
here is the XHTML page
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Pagina di test</title>
</h:head>
<body>
<h3>Pagina di test</h3>
<h:form>
<p:dataTable var="car" value="#{dtFilterView.cars}" widgetVar="carsTable"
emptyMessage="No cars found with given criteria" filteredValue="#{dtFilterView.filteredCars}">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search all fields:" />
<p:inputText id="globalFilter" onkeyup="PF('carsTable').filter()" style="width:150px" placeholder="Enter keyword"/>
</p:outputPanel>
</f:facet>
<p:column filterBy="#{car.id}" headerText="Id" footerText="contains" filterMatchMode="contains">
<h:outputText value="#{car.id}" />
</p:column>
<p:column filterBy="#{car.year}" headerText="Year" footerText="lte" filterMatchMode="lte">
<f:facet name="filter">
<p:spinner onchange="PF('carsTable').filter()" styleClass="year-spinner">
<f:converter converterId="javax.faces.Integer" />
</p:spinner>
</f:facet>
<h:outputText value="#{car.year}" />
</p:column>
<p:column filterBy="#{car.brand}" headerText="Brand" footerText="exact" filterMatchMode="exact">
<f:facet name="filter">
<p:selectOneMenu onchange="PF('carsTable').filter()" >
<f:selectItem itemLabel="Select One" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{dtFilterView.brands}" />
</p:selectOneMenu>
</f:facet>
<h:outputText value="#{car.brand}" />
</p:column>
<p:column filterBy="#{car.color}" headerText="Color" footerText="in" filterMatchMode="in">
<f:facet name="filter">
<p:selectCheckboxMenu label="Colors" onchange="PF('carsTable').filter()" panelStyle="width:125px" scrollHeight="150">
<f:selectItems value="#{dtFilterView.colors}" />
</p:selectCheckboxMenu>
</f:facet>
<h:outputText value="#{car.color}" />
</p:column>
<p:column filterBy="#{car.sold}" headerText="Status" footerText="equals" filterMatchMode="equals">
<f:facet name="filter">
<p:selectOneButton onchange="PF('carsTable').filter()">
<f:converter converterId="javax.faces.Boolean" />
<f:selectItem itemLabel="All" itemValue="" />
<f:selectItem itemLabel="Sold" itemValue="true" />
<f:selectItem itemLabel="Sale" itemValue="false" />
</p:selectOneButton>
</f:facet>
<h:outputText value="#{car.sold ? 'Sold': 'Sale'}" />
</p:column>
<p:column filterBy="#{car.price}" headerText="Price" footerText="custom (min)" filterFunction="#{dtFilterView.filterByPrice}">
<h:outputText value="#{car.price}">
<f:convertNumber currencySymbol="$" type="currency"/>
</h:outputText>
</p:column>
</p:dataTable>
</h:form>
</body>
</html>
here the Car.java
package controllers.test;
import java.io.Serializable;
public class Car implements Serializable {
public String id;
public String brand;
public int year;
public String color;
public int price;
public boolean sold;
public Car() {}
public Car(String id, String brand, int year, String color) {
this.id = id;
this.brand = brand;
this.year = year;
this.color = color;
}
public Car(String id, String brand, int year, String color, int price, boolean sold) {
this.id = id;
this.brand = brand;
this.year = year;
this.color = color;
this.price = price;
this.sold = sold;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public boolean isSold() {
return sold;
}
public void setSold(boolean sold) {
this.sold = sold;
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Car other = (Car) obj;
if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) {
return false;
}
return true;
}
}
then CarService.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "carService")
#ApplicationScoped
public class CarService {
private final static String[] colors;
private final static String[] brands;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
brands = new String[10];
brands[0] = "BMW";
brands[1] = "Mercedes";
brands[2] = "Volvo";
brands[3] = "Audi";
brands[4] = "Renault";
brands[5] = "Fiat";
brands[6] = "Volkswagen";
brands[7] = "Honda";
brands[8] = "Jaguar";
brands[9] = "Ford";
}
public List<Car> createCars(int size) {
List<Car> list = new ArrayList<Car>();
for(int i = 0 ; i < size ; i++) {
list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(), getRandomColor(), getRandomPrice(), getRandomSoldState()));
}
return list;
}
private String getRandomId() {
return UUID.randomUUID().toString().substring(0, 8);
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomBrand() {
return brands[(int) (Math.random() * 10)];
}
public int getRandomPrice() {
return (int) (Math.random() * 100000);
}
public boolean getRandomSoldState() {
return (Math.random() > 0.5) ? true: false;
}
public List<String> getColors() {
return Arrays.asList(colors);
}
public List<String> getBrands() {
return Arrays.asList(brands);
}
}
and last FilterView.java
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
#ManagedBean(name="dtFilterView")
#ViewScoped
public class FilterView implements Serializable {
private List<Car> cars;
private List<Car> filteredCars;
#ManagedProperty("#{carService}")
private CarService service;
#PostConstruct
public void init() {
cars = service.createCars(10);
}
public boolean filterByPrice(Object value, Object filter, Locale locale) {
String filterText = (filter == null) ? null : filter.toString().trim();
if(filterText == null||filterText.equals("")) {
return true;
}
if(value == null) {
return false;
}
return ((Comparable) value).compareTo(Integer.valueOf(filterText)) > 0;
}
public List<String> getBrands() {
return service.getBrands();
}
public List<String> getColors() {
return service.getColors();
}
public List<Car> getCars() {
return cars;
}
public List<Car> getFilteredCars() {
return filteredCars;
}
public void setFilteredCars(List<Car> filteredCars) {
this.filteredCars = filteredCars;
}
public void setService(CarService service) {
this.service = service;
}
}
The result is exactly the same, the filter are input field
I'm on glassfish 3.2
Sorry, I have my development environment with 5.0, but on production was 3.5
changing the library all worked

Reset p:tree selected values

I need to reset the selected values in a p:tree. I create a reset button in the form where i put my p:tree element. That button put the selected values of the tree as null values. In the backing bean the values are clear when i press this button. But in the interface even when I refresh the page the old selected value still marked. Here is my code:
p:tree
<p:tree id="treeClassifier"
value="#{navBarController.rootClassifier}"
var="node"
selectionMode="checkbox"
selection="#{navBarController.selectedClassifiers}"
style="height: 100px;width: 280px; margin-bottom: 0px; overflow: auto">
<p:treeNode expandedIcon="ui-icon-folder-open"
collapsedIcon="ui-icon-folder-collapsed">
<h:outputText value="#{node.description}(#{node.code})"/>
</p:treeNode>
</p:tree>
Create the tree:
public TreeNode initTree(GenericTree<Classifier> tree) {
GenericTreeNode<Classifier> root = tree.getRoot();
TreeNode rootJSF = new DefaultTreeNode("root", null);
for (GenericTreeNode<Classifier> gnt : root.getChildren()) {
if (gnt.getData().getId() != -1) {
TreeNode childTree = new DefaultTreeNode(gnt.getData(), rootJSF);
//rootJSF.getChildren().add(childTree);
//f_aux(gnt, rootJSF);
addChildsToTree(gnt, childTree);
}
}
return rootJSF;
}
public void addChildsToTree(GenericTreeNode<Classifier> parent, TreeNode parentJSF) {
for (GenericTreeNode<Classifier> child : parent.getChildren()) {
TreeNode newNode = new DefaultTreeNode(child.getData(), parentJSF);
//parentJSF.getChildren().add(newNode);
addChildsToTree(child, newNode);
}
}
The reset function:
public void reset() {
....
this.selectedClassifiers = null;
}
What is wrong in my code?
You can achieve by below example which method resetSelectedNode is used to fresh values.
xhtml
<h:form>
<p:growl id="msgs" showDetail="true" escape="false"/>
<p:inputText value="#{treeSelectionView.input}" />
<h3 style="margin-top:0">Single</h3>
<p:tree value="#{treeSelectionView.root1}"
id="simpleSelection"
var="doc"
selectionMode="single"
selection="#{treeSelectionView.selectedNode}"
dynamic="true">
<p:treeNode expandedIcon="ui-icon-folder-open"
collapsedIcon="ui-icon-folder-collapsed">
<h:outputText value="#{doc.name}"/>
</p:treeNode>
<p:treeNode type="document" icon="ui-icon-document">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="picture" icon="ui-icon-image">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="mp3" icon="ui-icon-video">
<h:outputText value="#{doc.name}" />
</p:treeNode>
</p:tree>
<p:commandButton value="Display"
update="msgs"
icon="ui-icon-newwin"
actionListener="#{treeSelectionView.displaySelectedSingle}"/>
<p:commandButton value="Reset"
update="simpleSelection"
icon="ui-icon-newwin"
process="#this"
actionListener="#{treeSelectionView.resetSelectedNode}" />
</h:form>
managedbean
#ManagedBean(name = "treeSelectionView")
#ViewScoped
public class SelectionView implements Serializable {
private TreeNode root1;
private TreeNode selectedNode;
private String input;
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
#ManagedProperty("#{documentService}")
private DocumentService service;
#PostConstruct
public void init() {
root1 = service.createDocuments();
}
public TreeNode getRoot1() {
return root1;
}
public TreeNode getSelectedNode() {
return selectedNode;
}
public void setSelectedNode(TreeNode selectedNode) {
this.selectedNode = selectedNode;
}
public void setService(DocumentService service) {
this.service = service;
}
public void displaySelectedSingle() {
System.out.println("input: " + input);
if (selectedNode != null) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected", selectedNode.getData().toString());
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
public void resetSelectedNode(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
ViewHandler viewHandler = application.getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(context, context.getViewRoot().getViewId());
context.setViewRoot(viewRoot);
context.renderResponse(); //Optional
}
}
See also: Clear Input Components
With these suggestions i realized that i need to reset the values from the selected array and update the nodes in the tree. So I made the following changes in my code:
public void reset() {
....
this.selectedClassifiers = null;
this.rootNode = initTree(tree);
}
public TreeNode initTree(GenericTree<Classifier> tree) {
GenericTreeNode<Classifier> root = tree.getRoot();
TreeNode rootJSF = new DefaultTreeNode("root", null);
rootJSF.setSelected(false);
for (GenericTreeNode<Classifier> gnt : root.getChildren()) {
if (gnt.getData().getId() != -1) {
TreeNode childTree = new DefaultTreeNode(gnt.getData(), rootJSF);
childTree.setSelected(false);
addChildsToTree(gnt, childTree);
}
}
return rootJSF;
}
public void addChildsToTree(GenericTreeNode<Classifier> parent, TreeNode parentJSF) {
for (GenericTreeNode<Classifier> child : parent.getChildren()) {
TreeNode newNode = new DefaultTreeNode(child.getData(), parentJSF);
newNode.setSelected(false);
addChildsToTree(child, newNode);
}
}
With these changes I fix my code.
Another example here.
XHTML
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<f:facet name="first">
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<meta name="viewport"
content="user-scalable=no,
width=device-width,
initial-scale=1.0,
maximum-scale=1.0"/>
</f:facet>
<title>Tree provides three selection modes, "single", "multiple" and "checkbox".</title>
</h:head>
<h:body id="bodyView">
<h:form>
<p:growl id="msgs" showDetail="true" escape="false"/>
<h3 style="margin-top:0">Single</h3>
<p:tree value="#{treeSelectionView.root1}"
id="simpleSelection"
var="doc"
selectionMode="single"
selection="#{treeSelectionView.selectedNode}">
<p:treeNode expandedIcon="ui-icon-folder-open"
collapsedIcon="ui-icon-folder-collapsed">
<h:outputText value="#{doc.name}"/>
</p:treeNode>
<p:treeNode type="document" icon="ui-icon-document">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="picture" icon="ui-icon-image">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="mp3" icon="ui-icon-video">
<h:outputText value="#{doc.name}" />
</p:treeNode>
</p:tree>
<p:commandButton value="Display"
update="msgs"
icon="ui-icon-newwin"
actionListener="#{treeSelectionView.displaySelectedSingle}"/>
<p:commandButton value="Reset"
update="simpleSelection"
icon="ui-icon-newwin"
process="#this"
actionListener="#{treeSelectionView.resetSelectedNode}" />
<h3>Multiple with metakey</h3>
<p:tree id="multipleSelection"
value="#{treeSelectionView.root1}"
var="doc"
selectionMode="multiple"
selection="#{treeSelectionView.selectedNodes1}">
<p:treeNode expandedIcon="ui-icon-folder-open"
collapsedIcon="ui-icon-folder-collapsed">
<h:outputText value="#{doc.name}"/>
</p:treeNode>
<p:treeNode type="document" icon="ui-icon-document">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="picture" icon="ui-icon-image">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="mp3" icon="ui-icon-video">
<h:outputText value="#{doc.name}" />
</p:treeNode>
</p:tree>
<p:commandButton value="Display"
update="msgs"
icon="ui-icon-newwin"
actionListener="#{treeSelectionView.displaySelectedMultiple(treeSelectionView.selectedNodes1)}"/>
<p:commandButton value="Reset"
update="multipleSelection"
icon="ui-icon-newwin"
process="#this"
actionListener="#{treeSelectionView.resetSelectedNode}" />
<h3>Multiple with Checkbox</h3>
<p:tree id="checkboxSelection"
value="#{treeSelectionView.root1}"
var="doc"
selectionMode="checkbox"
selection="#{treeSelectionView.selectedNodes2}">
<p:treeNode icon="ui-icon-note">
<h:outputText value="#{doc.name}"/>
</p:treeNode>
<p:treeNode type="document" icon="ui-icon-document">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="picture" icon="ui-icon-image">
<h:outputText value="#{doc.name}" />
</p:treeNode>
<p:treeNode type="mp3" icon="ui-icon-video">
<h:outputText value="#{doc.name}" />
</p:treeNode>
</p:tree>
<p:commandButton value="Display"
update="msgs"
icon="ui-icon-newwin"
actionListener="#{treeSelectionView.displaySelectedMultiple(treeSelectionView.selectedNodes2)}"/>
<p:commandButton value="Reset"
update="checkboxSelection"
icon="ui-icon-newwin"
process="#this"
actionListener="#{treeSelectionView.resetSelectedNode}" />
</h:form>
</h:body>
</html>
managedbean treeSelectionView
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.model.TreeNode;
import org.primefaces.showcase.service.DocumentService;
#ManagedBean(name = "treeSelectionView")
#ViewScoped
public class SelectionView implements Serializable {
private TreeNode root1;
private TreeNode root2;
private TreeNode root3;
private TreeNode selectedNode;
private TreeNode[] selectedNodes1;
private TreeNode[] selectedNodes2;
#ManagedProperty("#{documentService}")
private DocumentService service;
#PostConstruct
public void init() {
root1 = service.createDocuments();
root2 = service.createDocuments();
root3 = service.createDocuments();
}
public TreeNode getRoot1() {
return root1;
}
public TreeNode getRoot2() {
return root2;
}
public TreeNode getRoot3() {
return root3;
}
public TreeNode getSelectedNode() {
return selectedNode;
}
public void setSelectedNode(TreeNode selectedNode) {
this.selectedNode = selectedNode;
}
public TreeNode[] getSelectedNodes1() {
return selectedNodes1;
}
public void setSelectedNodes1(TreeNode[] selectedNodes1) {
this.selectedNodes1 = selectedNodes1;
}
public TreeNode[] getSelectedNodes2() {
return selectedNodes2;
}
public void setSelectedNodes2(TreeNode[] selectedNodes2) {
this.selectedNodes2 = selectedNodes2;
}
public void setService(DocumentService service) {
this.service = service;
}
public void displaySelectedSingle() {
if (selectedNode != null) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected", selectedNode.getData().toString());
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
public void displaySelectedMultiple(TreeNode[] nodes) {
if (nodes != null && nodes.length > 0) {
StringBuilder builder = new StringBuilder();
for (TreeNode node : nodes) {
builder.append(node.getData().toString());
builder.append("<br />");
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected", builder.toString());
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
public void resetSelectedNode(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
ViewHandler viewHandler = application.getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(context, context.getViewRoot().getViewId());
context.setViewRoot(viewRoot);
context.renderResponse(); //Optional
}
}
managedbean documentService
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.primefaces.showcase.domain.Document;
#ManagedBean(name = "documentService")
#ApplicationScoped
public class DocumentService {
public TreeNode createDocuments() {
TreeNode root = new DefaultTreeNode(new Document("Files", "-", "Folder"), null);
TreeNode documents = new DefaultTreeNode(new Document("Documents", "-", "Folder"), root);
TreeNode pictures = new DefaultTreeNode(new Document("Pictures", "-", "Folder"), root);
TreeNode movies = new DefaultTreeNode(new Document("Movies", "-", "Folder"), root);
TreeNode work = new DefaultTreeNode(new Document("Work", "-", "Folder"), documents);
TreeNode primefaces = new DefaultTreeNode(new Document("PrimeFaces", "-", "Folder"), documents);
//Documents
TreeNode expenses = new DefaultTreeNode("document", new Document("Expenses.doc", "30 KB", "Word Document"), work);
TreeNode resume = new DefaultTreeNode("document", new Document("Resume.doc", "10 KB", "Word Document"), work);
TreeNode refdoc = new DefaultTreeNode("document", new Document("RefDoc.pages", "40 KB", "Pages Document"), primefaces);
//Pictures
TreeNode barca = new DefaultTreeNode("picture", new Document("barcelona.jpg", "30 KB", "JPEG Image"), pictures);
TreeNode primelogo = new DefaultTreeNode("picture", new Document("logo.jpg", "45 KB", "JPEG Image"), pictures);
TreeNode optimus = new DefaultTreeNode("picture", new Document("optimusprime.png", "96 KB", "PNG Image"), pictures);
//Movies
TreeNode pacino = new DefaultTreeNode(new Document("Al Pacino", "-", "Folder"), movies);
TreeNode deniro = new DefaultTreeNode(new Document("Robert De Niro", "-", "Folder"), movies);
TreeNode scarface = new DefaultTreeNode("mp3", new Document("Scarface", "15 GB", "Movie File"), pacino);
TreeNode carlitosWay = new DefaultTreeNode("mp3", new Document("Carlitos' Way", "24 GB", "Movie File"), pacino);
TreeNode goodfellas = new DefaultTreeNode("mp3", new Document("Goodfellas", "23 GB", "Movie File"), deniro);
TreeNode untouchables = new DefaultTreeNode("mp3", new Document("Untouchables", "17 GB", "Movie File"), deniro);
return root;
}
}
domain
import java.io.Serializable;
public class Document implements Serializable, Comparable<Document> {
private String name;
private String size;
private String type;
public Document(String name, String size, String type) {
this.name = name;
this.size = size;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
//Eclipse Generated hashCode and equals
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((size == null) ? 0 : size.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Document other = (Document) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (size == null) {
if (other.size != null) {
return false;
}
} else if (!size.equals(other.size)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
#Override
public String toString() {
return name;
}
public int compareTo(Document document) {
return this.getName().compareTo(document.getName());
}
}
This is what I do in my projects :
I define this method, and call it whereever I want.
public static void resetAllInputChildren(String parentId) {
FacesContext currentInstance = FacesContext.getCurrentInstance();
if (currentInstance != null && currentInstance.getViewRoot() != null) {
RequestContext.getCurrentInstance().reset(parentId);
}
}
instead of the parentId, I normally set the form id. but it is your choice, you can set any component Id as the parentId.
One more thing, this is not a primefaces issue, the solution I suggested, applies to all jsf2 projects, and all input components.

On Primefaces datatable lazy loading complete update backing bean

I want to update backing bean after the primefaces datatable lazy loading is complete. I see that the API has a onSuccess & onComplete method for calling clientside code. But I would like to update backing bean based on the default selection. I have registered the "page" event with my datatable
<p:ajax event="page" update="" onstart="PF('loadingDialog').show()" onsuccess="PF('loadingDialog').hide()" listener=""/>
I could have used the listener but the problem is listener is invoked even before the server side loading method is complete.
RemoteCommand provides a simple way to execute backing bean methods with javascript.
The example is shown below.
xhtml
<h:form id="form">
<p:remoteCommand name="rc" update="msgs"
actionListener="#{remoteCommandView.execute('Wittakarn')}" />
<p:growl id="msgs" showDetail="true" />
<p:dataTable var="car" value="#{dtLazyView.lazyModel}"
paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink}
{PreviousPageLink}
{CurrentPageReport}
{NextPageLink}
{LastPageLink}"
rowsPerPageTemplate="5,10,15"
selectionMode="single"
selection="#{dtLazyView.selectedCar}"
id="carTable"
lazy="true">
<p:ajax event="rowSelect"
listener="#{dtLazyView.onRowSelect}"
update=":form:carDetail"
oncomplete="PF('carDialog').show()" />
<p:ajax event="page"
update=":form:carDetail"
oncomplete="rc()" />
<p:column headerText="Id"
sortBy="#{car.id}"
filterBy="#{car.id}">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year"
sortBy="#{car.year}"
filterBy="#{car.year}">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand"
sortBy="#{car.brand}"
filterBy="#{car.brand}">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color"
sortBy="#{car.color}"
filterBy="#{car.color}">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
<p:dialog header="Car Detail"
widgetVar="carDialog"
modal="true" showEffect="fade"
hideEffect="fade"
resizable="false">
<p:outputPanel id="carDetail"
style="text-align:center;">
<p:panelGrid columns="2"
rendered="#{not empty dtLazyView.selectedCar}"
columnClasses="label,value">
<f:facet name="header">
<p:graphicImage
name="demo/images/car/#{dtLazyView.selectedCar.brand}-big.gif"/>
</f:facet>
<h:outputText value="Id:" />
<h:outputText value="#{dtLazyView.selectedCar.id}" />
<h:outputText value="Year" />
<h:outputText value="#{dtLazyView.selectedCar.year}" />
<h:outputText value="Color:" />
<h:outputText value="#{dtLazyView.selectedCar.color}"
style="color:#{dtLazyView.selectedCar.color}"/>
<h:outputText value="Price:" />
<h:outputText value="#{dtLazyView.selectedCar.price}">
<f:convertNumber type="currency" currencySymbol="$" />
</h:outputText>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
managedbean
#ManagedBean
public class RemoteCommandView {
public void execute() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Executed", "Using RemoteCommand."));
}
public void execute(String detail) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, detail, "Using RemoteCommand."));
}
}
#ManagedBean(name="dtLazyView")
#ViewScoped
public class LazyView implements Serializable {
private LazyDataModel<Car> lazyModel;
private Car selectedCar;
#ManagedProperty("#{carService}")
private CarService service;
#PostConstruct
public void init() {
lazyModel = new LazyCarDataModel(service.createCars(200));
}
public LazyDataModel<Car> getLazyModel() {
return lazyModel;
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public void setService(CarService service) {
this.service = service;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
model
public class Car implements Serializable {
public String id;
public String brand;
public int year;
public String color;
public int price;
public boolean sold;
public Car() {}
public Car(String id, String brand, int year, String color) {
this.id = id;
this.brand = brand;
this.year = year;
this.color = color;
}
public Car(String id, String brand, int year, String color, int price, boolean sold) {
this.id = id;
this.brand = brand;
this.year = year;
this.color = color;
this.price = price;
this.sold = sold;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public boolean isSold() {
return sold;
}
public void setSold(boolean sold) {
this.sold = sold;
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Car other = (Car) obj;
if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) {
return false;
}
return true;
}
}
carService
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.primefaces.showcase.domain.Car;
#ManagedBean(name = "carService")
#ApplicationScoped
public class CarService {
private final static String[] colors;
private final static String[] brands;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
brands = new String[10];
brands[0] = "BMW";
brands[1] = "Mercedes";
brands[2] = "Volvo";
brands[3] = "Audi";
brands[4] = "Renault";
brands[5] = "Fiat";
brands[6] = "Volkswagen";
brands[7] = "Honda";
brands[8] = "Jaguar";
brands[9] = "Ford";
}
public List<Car> createCars(int size) {
List<Car> list = new ArrayList<Car>();
for(int i = 0 ; i < size ; i++) {
list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(), getRandomColor(), getRandomPrice(), getRandomSoldState()));
}
return list;
}
private String getRandomId() {
return UUID.randomUUID().toString().substring(0, 8);
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomBrand() {
return brands[(int) (Math.random() * 10)];
}
private int getRandomPrice() {
return (int) (Math.random() * 100000);
}
private boolean getRandomSoldState() {
return (Math.random() > 0.5) ? true: false;
}
public List<String> getColors() {
return Arrays.asList(colors);
}
public List<String> getBrands() {
return Arrays.asList(brands);
}
}
You can see more detail: RemoteCommand
Since I prefer using vanilla JSF, I would do the following
put this above your table
<h:commandButton id="call-me-after-page"
style="display:none;" action="#{myBean.myAction}">
<f:ajax execute="#form" render="#form"></f:ajax>
</h:commandButton>
and set the oncomplete like this:
<p:ajax event="page" oncomplete="$('#call-me-after-page').click();"></p:ajax>