I have some trouble using Primefaces autoComplete feature. First I would like to show my xhtml file.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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:f="http://java.sun.com/jsf/core"
xmlns:o="http://openfaces.org/"
xmlns:om="http://omnifaces.org/ui"
xmlns:of="http://omnifaces.org/functions"
xmlns:p="http://primefaces.org/ui" >
<ui:composition template="/Template/basicTemplate.xhtml">
<ui:define name="content">
<h:form> <h1>Firma anlegen</h1>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="name" value="Name:" style="font-weight:bold" />
<p:inputText id="name" value="#{registerCompanyBean.company.name}" />
<h:outputLabel for="name" value="Straße:" style="font-weight:bold" />
<p:inputText id="street" value="#{registerCompanyBean.postalAddress.street}" />
<h:outputLabel for="name" value="PLZ:" style="font-weight:bold" />
<p:inputText id="zipCode" value="#{registerCompanyBean.postalAddress.zipCode}" />
<h:outputLabel for="name" value="Ort:" style="font-weight:bold" />
<p:inputText id="city" value="#{registerCompanyBean.postalAddress.city}" />
<h:outputLabel for="name" value="Land:" style="font-weight:bold" />
<p:inputText id="country" value="#{registerCompanyBean.postalAddress.country}" />
<p:outputLabel value="Branche:" for="dd" style="font-weight:bold" />
<p:autoComplete id="dd" dropdown="true" value="#{registerCompanyBean.buisnessCategory.name}" completeMethod="#{registerCompanyBean.completeBuisnessCategory}"
var="buisnessCategory" itemLabel="#{buisnessCategory.name}" itemValue="#{buisnessCategory}" converter="buisnessCategoryConverter" forceSelection="true" >
</p:autoComplete>
</h:panelGrid>
<H1>Wartelisten</H1>
<h:panelGrid columns="2" cellpadding="5">
</h:panelGrid>
<p:commandButton id="save" value="Save" action="#{registerCompanyBean.save}" ajax="false"/>
</h:form>
</ui:define>
</ui:composition>
</html>
The Page start without any Error. I can fill in the input fields and I can use the drop-down Box as aspected. I can even use the autoComplete function but when I push the CommandButton I get a NullPointerException. If I remove the ajax attribute of the commandButton, the CommandButton does nothing ( no function call at all). So for me it seems that I have to add the ajax=false attribute.
Any Ideas???
Thx
Michael Schmidt
For better understanding I add all the other files.
The Converter:
/**
*
* #author mibschmidt
*/
#FacesConverter("buisnessCategoryConverter")
public class BuisnessCategoryConverter implements Converter{
#Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if(value != null && value.trim().length() > 0) {
try {
BuisnessCategoryService service = (BuisnessCategoryService) fc.getExternalContext().getApplicationMap().get("buisnessCategoryService");
return service.findAll().get(Integer.parseInt(value));
} catch(NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid BuisnessCategory."));
}
}
else {
return null;
}
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object object) {
if(object != null) {
return String.valueOf(((BuisnessCategory) object).getID());
}
else {
return null;
}
}
}
The ManageBean:
#Controller
#Scope("session")
public class RegisterCompanyBean extends GenericCRUDController<Company, CompanyService> implements Serializable {
#Autowired
private BuisnessCategoryService buisnessCategoryService;
private BuisnessCategory buisnessCategory;
public BuisnessCategoryService getBuisnessCategoryService() {
return buisnessCategoryService;
}
public void setBuisnessCategoryService(BuisnessCategoryService buisnessCategoryService) {
this.buisnessCategoryService = buisnessCategoryService;
}
public BuisnessCategory getBuisnessCategory() {
return buisnessCategory;
}
public void setBuisnessCategory(BuisnessCategory buisnessCategory) {
this.buisnessCategory = buisnessCategory;
}
#Autowired
private PostalAddressService postalAddressService;
private PostalAddress postalAddress =new PostalAddress();
public PostalAddressService getPostalAddressService() {
return postalAddressService;
}
public void setPostalAddressService(PostalAddressService postalAddressService) {
this.postalAddressService = postalAddressService;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
#Autowired
private CompanyService companyService;
private Company company= new Company();
public PostalAddress getPostalAddress() {
return postalAddress;
}
public void setPostalAddress(PostalAddress postalAddress) {
this.postalAddress = postalAddress;
}
public CompanyService getCompanyService() {
return companyService;
}
public void setCompanyService(CompanyService companyService) {
this.companyService = companyService;
}
public List<BuisnessCategory> getBuisnessCategoryList() {
return buisnessCategoryService.findAll();
}
#Override
protected CompanyService getService() {
return companyService;
}
public void saveButtonAction(ActionEvent actionEvent) {
addMessage("Speichern der Firma");
}
#Override
public String save() {
List <PostalAddress> pAL = new ArrayList<>();
pAL.add(postalAddressService.save(postalAddress));
company.setPostalAddress(pAL);
company.setBuisnessCategory(buisnessCategoryService.save(buisnessCategory));
company=companyService.save(company);
if(company==null){
addMessage("Fehler beim Registrieren der Firma");
}else{
addMessage(String.valueOf(company.getID()));
}
return super.save(); //To change body of generated methods, choose Tools | Templates.
}
public List<BuisnessCategory> completeBuisnessCategory(String query) {
List<BuisnessCategory> allBuisnessCategory = buisnessCategoryService.findAll();
List<BuisnessCategory> filteredBuisnessCategory = new ArrayList<>();
for (int i = 0; i < allBuisnessCategory.size(); i++) {
BuisnessCategory bk = allBuisnessCategory.get(i);
if(bk.getName().toLowerCase().contains(query.toLowerCase())) {
filteredBuisnessCategory.add(bk);
}
}
return filteredBuisnessCategory;
}
public void addMessage(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
The Error Message:
at com.wedusch.waitlist.jsf.util.BuisnessCategoryConverter.getAsObject(BuisnessCategoryConverter.java:33)
at org.primefaces.component.autocomplete.AutoCompleteRenderer.getConvertedValue(AutoCompleteRenderer.java:604)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
You must initial object(buisnessCategory) before usage(#{registerCompanyBean.buisnessCategory.name}).
Initial at constructor
public RegisterCompanyBean(){
buisnessCategory = new BuisnessCategory();
}
Or initial by #PostConstruct
#PostConstruct
public void init(){
buisnessCategory = new BuisnessCategory();
}
Related
I want to trigger a method when a text field is blurred, and so I added an Ajax onblur event to this text field, and it works.
The problem I am having is with the commandButton that submits a bean with NULL fields.
When I get rid of the inputText Ajax event, the form submission works as usual.
The .xhtml file:
`
<h:head>
<title>Saisie Cotisations</title>
</h:head>
<h:body>
<h3>Saisie Cotisation</h3>
<h:form id="formulaire">
<h:panelGroup>
<p:panelGrid columns="2" id="panelMenage" >
<p:outputLabel value="N° Appartement" for="appart" />
<p:inputNumber id="appart" value="#{saisieBean.menage.numAppart}" decimalPlaces="0" emptyValue="empty" size="3" thousandSeparator="" >
<p:ajax event="blur" listener="#{saisieBean.chargerMenage}" update="panelMenage panelCotisation" />
</p:inputNumber>
<p:outputLabel value="Nom" for="nom" />
<p:inputText id="nom" value="#{saisieBean.menage.nom}" disabled="#{saisieBean.lectureSeule}" >
</p:inputText>
<p:outputLabel value="Prenom" for="prenom" />
<p:inputText id="prenom" value="#{saisieBean.menage.prenom}" disabled="#{saisieBean.lectureSeule}" >
</p:inputText>
<p:outputLabel value="Adresse E-Mail" for="email" />
<p:inputText id="email" value="#{saisieBean.menage.email}" disabled="#{saisieBean.lectureSeule}" >
</p:inputText>
</p:panelGrid>
</h:panelGroup>
<br />
<h:panelGroup>
<p:panelGrid columns="2" id="panelCotisation" >
<p:outputLabel value="Type Cotisation" />
<p:selectOneMenu value="#{saisieBean.menage.cotisation.id}" disabled="#{saisieBean.lectureSeule}" >
<f:selectItems value="#{saisieBean.typesCotisation}" var="tc" itemValue="#{tc.id}" itemLabel="#{tc.intitule}" />
</p:selectOneMenu>
<p:outputLabel value="Mois" />
<p:selectOneMenu value="#{saisieBean.mois}" disabled="#{saisieBean.lectureSeule}" >
<f:selectItems value="#{saisieBean.listeMois}" />
</p:selectOneMenu>
<p:outputLabel value="Annee" />
<p:inputNumber value="#{saisieBean.menage.cotisation.annee}" decimalPlaces="0" thousandSeparator="" disabled="#{saisieBean.lectureSeule}" />
<p:outputLabel value="Montant" />
<p:inputNumber value="#{saisieBean.menage.cotisation.montant}" decimalPlaces="2" disabled="#{saisieBean.lectureSeule}" />
</p:panelGrid>
</h:panelGroup>
<br />
<p:commandButton value="Soumettre" actionListener="#{saisieBean.exec}" process="#form" update="#form" immediate="false" ></p:commandButton>
</h:form>
</h:body>
`
The Bean:
package ma.syndic.bean;
import java.io.Serializable;
import java.text.DateFormatSymbols;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
import ma.syndic.back.bean.Cotisation;
import ma.syndic.back.bean.Menage;
import ma.syndic.back.bean.TypeCotisation;
import ma.syndic.back.dao.bean.MenageDAO;
import ma.syndic.back.dao.bean.TypeCotisationDAO;
import org.joda.time.DateTime;
/**
*
* #author Mohamed ENNAHDI EL IDRISSI
* #date 13/11/2016
*/
#ManagedBean
#ViewScoped
public class SaisieBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5492998931983521852L;
private Menage menage;
private Cotisation cotisation;
private List<TypeCotisation> typesCotisation;
private String[] listeMois;
private String mois;
private boolean lectureSeule = true;
public SaisieBean() {
// TODO Auto-generated constructor stub
}
#PostConstruct
public void init() {
this.menage = new Menage();
this.cotisation = new Cotisation();
try {
this.typesCotisation = new TypeCotisationDAO().findAll();
} catch (Exception e) {
e.printStackTrace();
}
this.listeMois = new DateFormatSymbols().getMonths();
int i = new DateTime().monthOfYear().get();
this.mois = this.listeMois[ i - 1 ];
this.menage.getCotisation().setAnnee(new DateTime().year().get());
}
public void exec() {
System.out.println("Exec fired");
System.out.println("EMail: " + this.menage.getEmail());
}
public void chargerMenage() {
System.out.println("chargerMenage fired");
if (this.menage.getNumAppart() != null) {
this.lectureSeule = false;
try {
Menage m = new MenageDAO().find(this.menage);
if (m != null) {
this.menage = m;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Menage getMenage() {
return menage;
}
public void setMenage(Menage menage) {
this.menage = menage;
}
public Cotisation getCotisation() {
return cotisation;
}
public void setCotisation(Cotisation cotisation) {
this.cotisation = cotisation;
}
public List<TypeCotisation> getTypesCotisation() {
return typesCotisation;
}
public void setTypesCotisation(List<TypeCotisation> typesCotisation) {
this.typesCotisation = typesCotisation;
}
public String[] getListeMois() {
return listeMois;
}
public void setListeMois(String[] listeMois) {
this.listeMois = listeMois;
}
public String getMois() {
return mois;
}
public void setMois(String mois) {
this.mois = mois;
}
public boolean isLectureSeule() {
return lectureSeule;
}
public void setLectureSeule(boolean lectureSeule) {
this.lectureSeule = lectureSeule;
}
}
im using hibernate 4, spring 4, lucene 3, primefaces 5, java 7.
I got a data table, which data is populated on the baking bean, the idea with the table is that it shows me some uncategorized words, and lets me categorizate them.
an example of the initial table looks normal for example
1 2 3 4 5
here is my page
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:form id="form">
<p:growl id="msgs" showDetail="true" life="2000" />
<p:dataTable id="words" var="word"
value="#{wordCatalogatorController.unknownWords}" editable="true"
style="margin-bottom:20px">
<f:facet name="header">Row Editing</f:facet>
<p:ajax event="rowEdit"
listener="#{wordCatalogatorController.onRowEdit}" update=":form:msgs" />
<p:ajax event="rowEditCancel"
listener="#{wordCatalogatorController.onRowCancel}" update=":form:msgs" />
<p:column headerText="Palabra">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{word.word}" />
</f:facet>
<f:facet name="input">
<h:outputText value="#{word.word}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Tipo Palabra">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{word.wordType}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{word.wordType}" style="width:100%"
converter="#{wordTypeConverter}">
<f:selectItems value="#{wordCatalogatorController.wordTypes}"
var="man" itemLabel="#{man.wordType}" itemValue="#{man}" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</html>
the bean for this is:
#Controller
#Transactional
public class WordCatalogatorController {
private List<Word> unknownWords = new ArrayList<Word>();
private List<WordType> wordTypes = new ArrayList<WordType>();
public WordCatalogatorController(){
//inicializamos palabras desconocidas y tipos de palabras!
for(int i = 0 ; i < 6 ; i++){
unknownWords.add(new Word("" + i));
}
for(int i = 0 ; i < 4 ; i++){
wordTypes.add(new WordType("" + i));
}
}
public void onRowEdit(RowEditEvent event) {
Word currentWord = (Word) event.getObject();
unknownWords.remove(currentWord);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edit Cancelled",
((Word) event.getObject()).getWord());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if (newValue != null && !newValue.equals(oldValue)) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Cell Changed", "Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
then after editing and saving the first row (1) the datatables updates with 1 2 2 3 4 5
Any ideas will be really apreciated!
here comes the code for pojo clases
#Entity
#Table(name="Word")
#Indexed
#AnalyzerDef(name = "searchtokenanalyzer",tokenizer = #TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
#TokenFilterDef(factory = StandardFilterFactory.class),
#TokenFilterDef(factory = LowerCaseFilterFactory.class),
#TokenFilterDef(factory = StopFilterFactory.class,params = {
#Parameter(name = "ignoreCase", value = "true") }) })
#Analyzer(definition = "searchtokenanalyzer")
public class Word {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long wordId;
#Column(name="word")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#Analyzer(definition="searchtokenanalyzer")
private String word;
#ManyToMany(mappedBy="words")
private Collection<Danger> dangers = new ArrayList<Danger>();
#ManyToMany(mappedBy="words")
private Collection<Risk> risks = new ArrayList<Risk>();
#ManyToMany(mappedBy="words")
private Collection<Control> controls = new ArrayList<Control>();
#ManyToOne
#JoinColumn(name = "wordTypeId")
private WordType wordType;
public Word(String word, WordType wordType) {
super();
this.word = word;
this.wordType = wordType;
}
public Word(String word) {
super();
this.word = word;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof Word){
return ((Word)obj).getWord().equalsIgnoreCase(this.getWord());
}else{
return false;
}
}
public Word() {
super();
}
public long getWordId() {
return wordId;
}
public void setWordId(long wordId) {
this.wordId = wordId;
}
#Entity
#Table(name = "WordType")
#Indexed
public class WordType {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long wordTypeId;
#Column(name = "wordType")
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
#Analyzer(definition = "searchtokenanalyzer")
private String wordType;
#Column(name = "description")
private String description;
#OneToMany(mappedBy = "wordType")
private Set<Word> words;
#Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if (!(obj instanceof WordType)) {
return false;
} else {
WordType extenalWT = (WordType) obj;
if (this.wordType.equalsIgnoreCase(extenalWT.getWordType())
&& this.wordTypeId == extenalWT.getWordTypeId()) {
return true;
} else {
return false;
}
}
}
public WordType() {
}
public WordType(String wordType) {
this.wordType = wordType;
}
public long getWordTypeId() {
return wordTypeId;
}
public void setWordTypeId(long wordTypeId) {
this.wordTypeId = wordTypeId;
}
public String getWordType() {
return wordType;
}
public void setWordType(String wordType) {
this.wordType = wordType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Word> getWords() {
return words;
}
public void setWords(Set<Word> words) {
this.words = words;
}
#Override
public String toString() {
return wordType;
}
}
For anyone else having this issue:
It seems to be an issue between the rowEditor and the table sorting. Having the correct update target on the ajax tag isn't an issue as the row is technically removed but the display gets messed up. You can get around this with just a touch of nastiness. You can force a filter during oncomplete for the ajax tag. This will get rid of the ghost duplicate record.
<p:ajax event="rowEdit"
listener="#{beanName.onRowEdit}"
update=":growl :messages :formName:tableId"
oncomplete="PF('tableWidgetVar').filter();" />
Finally the best solution was to implement the select event for the data table, and in the event have a dialog to pick the option, then refresh the table, this is the final xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:form id="myForm">
<p:growl id="msgs" showDetail="true" life="2000" />
<p:panel header="Sale Item" style="width: 400px;">
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Texto" for="acSimple" />
<p:autoComplete id="acSimple"
value="#{wordCatalogatorController.texto}"
completeMethod="#{wordCatalogatorController.completeText}"
binding="#{wordCatalogatorController.autoCompleteText}" />
<p:commandButton value="Guardar actividad" id="save"
update=":myForm:msgs words"
binding="#{wordCatalogatorController.saveButton}"
actionListener="#{wordCatalogatorController.saveActivity}"
styleClass="ui-priority-primary" process="#this" />
</h:panelGrid>
<p:dataTable id="words" widgetVar="words" var="word"
value="#{wordCatalogatorController.unknownWords}" editable="true"
style="margin-bottom:20px" rowKey="#{word.word}"
selection="#{wordCatalogatorController.selectedWord}"
selectionMode="single" editMode="row">
<p:ajax event="rowSelect"
listener="#{wordCatalogatorController.changeClient}"
oncomplete="PF('activityDialog').show()"
update=":myForm:activityDialog" />
<f:facet name="header">Edicion de palabras</f:facet>
<p:column headerText="Palabra">
<h:outputText value="#{word.word}" />
</p:column>
<p:column headerText="Edicion">
<h:outputText value="Presione para catalogar la palabra" />
</p:column>
</p:dataTable>
</p:panel>
<p:dialog id="activityDialog" width="500px" height="600px"
header="Palabra a catalogar: #{wordCatalogatorController.selectedWord.word}"
widgetVar="activityDialog" modal="true" closable="false">
<h:panelGrid columns="2" cellpadding="5">
<p:selectOneMenu id="wordTypes"
value="#{wordCatalogatorController.selectedWordType}"
style="width: 150px;" converter="#{wordTypeConverter}">
<p:ajax
listener="#{wordCatalogatorController.wordTypeChangeListener}"
update=":myForm:words" />
<f:selectItem itemLabel="" itemValue="" />
<f:selectItems value="#{wordCatalogatorController.wordTypes}" />
</p:selectOneMenu>
</h:panelGrid>
</p:dialog>
</h:form>
</h:body>
</html>
I'm using a selectOneMenu and i want to update datatable depending on what i choose on the combobox, i have two tables on the database:
Fournisseur
idFournisseur
raisonSociale
telephone..
and
Devis
idDevis
idFournisseur
devis.xhtml
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
<p:outputLabel for="console" value="Basic:" />
<p:selectOneMenu id="console" value="#{fournisseurBean.raisonSociale}">
<f:selectItems value="#{fournisseurBean.listeFournisseurs}" var="fournisseur" itemValue="#{fournisseur}" itemLabel="#{fournisseur.raisonSociale}" />
<p:ajax event="change" update="display" listener="#{fournisseurBean.getFournisseurByRaison()}" />
</p:selectOneMenu>
<p:dataTable id="display" var="listeDevis" value="#{devisBean.listeDevis}" editable="true" style="margin-bottom:10px">
<f:facet name="header">
Liste des devis
</f:facet>
<p:ajax event="rowEdit" listener="#{dtEditView.onRowEdit}" update=":form:msgs" />
<p:ajax event="rowEditCancel" listener="#{dtEditView.onRowCancel}" update=":form:msgs" />
<p:column headerText="Id devis">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeDevis.idDevis}" /></f:facet>
<f:facet name="input"><p:inputText id="modelInput" value="#{listeDevis.idDevis}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Date devis">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeDevis.dateDevis}" /></f:facet>
<f:facet name="input"><p:inputText value="#{listeDevis.dateDevis}" style="width:100%" label="Year"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px" headerText="Modification">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
FournisseurBean.xhtml
package controller;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.event.ValueChangeEvent;
import model.services.FournisseurMetier;
import net.vo.Fournisseur;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#Scope("view")
public class FournisseurBean {
#Autowired
private FournisseurMetier fournisseurMetier;
private List<Fournisseur> listeFournisseurs;
private List<String> listeRaisons;
private int idFournisseur;
private String raisonSociale;
private String rib;
private String adresse;
private Long telephone;
#PostConstruct
public void init() {
listeFournisseurs = fournisseurMetier.getAllFournisseurs();
listeRaisons = fournisseurMetier.getAllRaisonsSociales();
}
public List<Fournisseur> getListeFournisseurs() {
return listeFournisseurs;
}
public void insert()
{
Fournisseur fournisseur = new Fournisseur();
fournisseur.setIdFournisseur(getIdFournisseur());
fournisseur.setRaisonSociale(getRaisonSociale());
fournisseur.setRib(getRib());
fournisseur.setAdresse(getAdresse());
fournisseur.setTelephone(getTelephone());
fournisseurMetier.insert(fournisseur);
}
public void update()
{
Fournisseur fournisseuur = fournisseurMetier.getFournisseur(this.idFournisseur);
fournisseuur.setRaisonSociale(getRaisonSociale());
fournisseuur.setRib(getRib());
fournisseuur.setAdresse(getAdresse());
fournisseuur.setTelephone(getTelephone());
fournisseurMetier.update(fournisseuur);
}
public FournisseurMetier getFournisseurMetier() {
return fournisseurMetier;
}
public void setFournisseurMetier(FournisseurMetier fournisseurMetier) {
this.fournisseurMetier = fournisseurMetier;
}
public void setListeFournisseurs(List<Fournisseur> listeFournisseurs) {
this.listeFournisseurs = listeFournisseurs;
}
public int getIdFournisseur() {
return idFournisseur;
}
public void setIdFournisseur(int idFournisseur) {
this.idFournisseur = idFournisseur;
}
public String getRaisonSociale() {
return raisonSociale;
}
public void setRaisonSociale(String raisonSociale) {
this.raisonSociale = raisonSociale;
}
public String getRib() {
return rib;
}
public void setRib(String rib) {
this.rib = rib;
}
public Long getTelephone() {
return telephone;
}
public void setTelephone(Long telephone) {
this.telephone = telephone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public String toString() {
return "FournisseurBean{" + "raisonSociale=" + raisonSociale + '}';
}
public void getFournisseurByRaison()
{
System.out.println(raisonSociale);
}
}
This method getFournisseurByRaison() shows me a reference to object Fournisseur not the attribute raisonSociale.
You can sue p:ajax as you mentioned in comments.
OR
Since you are using Primefaces you can also Update any component from ManagedBean itself using org.primefaces.context.RequestContext object.
For example:
Facelet:
<h:form id="form1">
<p:dataTable id="myTab">
...
</p:dataTable>
</h:form>
ManagedBean:
RequestContext reqCtx = Requestcontext.getCurrentInstance();
req.Ctx.update("form1:myTab");
this method getFournisseurByRaison() shows me a reference to object Fournisseur not the attribure raisonSociale
This is because you're setting the object as the value:
<!-- itemValue="#{fournisseur}" <= here is the object set as value -->
<f:selectItems value="#{fournisseurBean.listeFournisseurs}"
var="fournisseur"
itemValue="#{fournisseur}"
itemLabel="#{fournisseur.raisonSociale}" />
You should use an identifier or another field to be able to seek the selected fournisseur from the values of the list. This may be a starting approach:
<!-- itemValue="#{fournisseur.id}" <= or another unique identifier field -->
<f:selectItems value="#{fournisseurBean.listeFournisseurs}"
var="fournisseur"
itemValue="#{fournisseur.id}"
itemLabel="#{fournisseur.raisonSociale}" />
Then, in your bean:
public void getFournisseurByRaison() {
System.out.println(raisonSociale); //will print the user selected id or unique identifier
//access to devisBean and update the data in `devisBean.listeDevis` in there
}
I have the following xhtml page where there is a form where the user have to select the location where he wants to travel; choosing it from a selectionmenu, the panel "Volo" is updated by an action listener and it will contain another selectionmenu where all flights to that location are available. I'd like to select the Hotels and Escursions available between the starting and ending date of the flight, so i used an action listener to update the panel containing the two activities based on the flight chosen. I'd like to know where i'm mistaking and if it's possible to have multiple updates of this kind in a single page.
I post the code of the xhtml page:
<!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:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:panel header="DefaultPackage Form">
<h:panelGrid columns="3" id="regGrid">
<h:outputLabel for="Name">Name:</h:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<h:outputLabel for="location">Locations Available:</h:outputLabel>
<h:selectOneMenu for="location" value="#{addDefaultPackageBean.defpackDTO.location}">
<f:ajax listener="#{addDefaultPackageBean.Search()}" render=":form:Volo" />
<f:selectItems id="location" value="#{addDefaultPackageBean.availableLocations}" />
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
<p:panel header="Voli Disponibili per la location selezionata" id="Volo" rendered="#{addDefaultPackageBean.flag}" >
<h:outputLabel for="Fly">Volo:</h:outputLabel>
<h:selectOneMenu for="Fly" value="#{addDefaultPackageBean.fly}">
<f:ajax listener="#{addDefaultPackageBean.sel()}" render=":form:regularGrid" />
<f:selectItems id="Fly" value="#{addDefaultPackageBean.elelisfly}"
var="ElementDTO" itemValue="#{ElementDTO.name}"
itemLabel="#{ElementDTO.name}" />
</h:selectOneMenu>
</p:panel>
<p:panel header="HotelEsc" id="HotelEscursioni">
<h:panelGrid columns="3" id="regularGrid" rendered="#{addDefaultPackageBean.flagdopo}">
<h:outputLabel for="Hotel">Hotel:</h:outputLabel>
<h:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</h:selectOneMenu>
<p:message for="Hotel" />
<h:outputLabel for="Escursion">Escursioni:</h:outputLabel>
<f:facet name="header">Clicca su view per vedere i dettagli</f:facet>
<p:dataTable id="Escursion" var="esc"
value="#{addDefaultPackageBean.elelisescursion}"
rowKey="#{esc.name}"
selection="#{addDefaultPackageBean.selectedEscursions}"
selectionMode="multiple">
<p:column headerText="Nome"> #{esc.name} </p:column>
<p:column headerText="Costo"> #{esc.cost} </p:column>
<p:column headerText="Data Iniziale"> #{esc.startingDate} </p:column>
<p:column headerText="Data Fine"> #{esc.endingDate} </p:column>
<f:facet name="footer">
<p:commandButton value="View" icon="ui-icon-search"
oncomplete="PF('escursionDialog').show()" />
</f:facet>
</p:dataTable>
<p:dialog header="Escursion Detail" widgetVar="escursionDialog"
width="250" showEffect="explode" hideEffect="explode">
<p:dataList id="display"
value="#{addDefaultPackageBean.selectedEscursions}"
var="selectedEsc" type="definition">
Nome: #{selectedEsc.name}, Description: #{selectedEsc.description}
</p:dataList>
</p:dialog>
</h:panelGrid>
</p:panel>
<p:commandButton value="Add" update="regGrid"
action="#{addDefaultPackageBean.add()}" />
</h:form>
</h:body>
</html>
Bean page:
package beans;
import java.awt.Event;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.view.ViewScoped;
import elementManagement.ElementMgr;
import elementManagementDTO.ElementDTO;
import DefaultPackageManagement.DefaultPackageMgr;
import DefaultPackageManagementDTO.DefaultPackageDTO;
#ManagedBean(name="addDefaultPackageBean") //come viene richiamato
#ViewScoped
public class AddDefaultPackageBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
private DefaultPackageMgr defpackMgr;
private DefaultPackageDTO defpackDTO;
private ArrayList<ElementDTO> elelisfly;
private ArrayList<ElementDTO> elelishotel;
private ArrayList<ElementDTO> elelisescursion;
private ArrayList<ElementDTO> elelis;
private ElementDTO[] selectedEscursions;
private String fly;
private String hotel;
private boolean flag=true;
private boolean flagdopo=true;
private ArrayList<String> availableLocations;
private ElementDTO flyElem;
#EJB
private ElementMgr elemMgr;
public ElementDTO[] getSelectedEscursions() {
return selectedEscursions;
}
public void setSelectedEscursions(ElementDTO[] selectedEscursions) {
this.selectedEscursions = selectedEscursions;
}
public AddDefaultPackageBean() {
defpackDTO = new DefaultPackageDTO();
}
#PostConstruct
public void init()
{
this.elelisfly=new ArrayList<ElementDTO>();
this.elelishotel=new ArrayList<ElementDTO>();
this.elelisescursion=new ArrayList<ElementDTO>();
this.setElelis(elemMgr.getAllElements());
this.availableLocations=new ArrayList<String>();
for(ElementDTO e:elelis)
{
if (this.availableLocations.contains(e.getLocation())==false)
{
this.availableLocations.add(e.getLocation());
}
}
}
public String add() {
this.AssignElemFlyFromSelection();
this.AssignElemHotelFromSelection();
this.AssignElemEscursionFromSelection();
defpackMgr.save(defpackDTO);
return "/employee/index?faces-redirect=true";
}
public void sel()
{
System.out.print("ehila" );
this.AssignElemFlyFromSelection();
this.elelisescursion.clear();
this.elelishotel.clear();
for(ElementDTO e:elelis)
{
System.out.print("ho un hotel tra gli elementi "+e.getName() );
if(e.getType().equals("Hotel"))
{
System.out.print("ho un hotel tra gli elementi "+e.getName() );
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&(e.getEndingDate().before(this.flyElem.getEndingDate())))
{
System.out.print("ho un hotel tra gli elementi con le date giuste"+e.getName());
this.getElelishotel().add(e);
}
}
else
{
if(e.getType().equals("Escursion"))
{
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&(e.getEndingDate().before(this.flyElem.getEndingDate())))
{
this.getElelishotel().add(e);
}
}
}
}
this.setFlagdopo(true);
}
public DefaultPackageDTO getDefpackDTO() {
return defpackDTO;
}
public void setDefpackDTO(DefaultPackageDTO defpackDTO) {
this.defpackDTO = defpackDTO;
}
public ArrayList<ElementDTO> getElelisfly() {
return elelisfly;
}
public void setElelisfly(ArrayList<ElementDTO> elelisfly) {
this.elelisfly = elelisfly;
}
public ArrayList<ElementDTO> getElelishotel() {
return elelishotel;
}
public void setElelishotel(ArrayList<ElementDTO> elelishotel) {
this.elelishotel = elelishotel;
}
public ArrayList<ElementDTO> getElelisescursion() {
return elelisescursion;
}
public void setElelisescursion(ArrayList<ElementDTO> elelisescursion) {
this.elelisescursion = elelisescursion;
}
public String getFly() {
return fly;
}
public void setFly(String fly) {
this.fly = fly;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
private void AssignElemFlyFromSelection()
{
for (ElementDTO elem:this.elelisfly)
{
if(elem.getName().equals(this.fly))
{
this.flyElem=elem;
}
}
}
private void AssignElemHotelFromSelection()
{
for (ElementDTO elem:this.elelishotel)
{
if(elem.getName().equals(this.hotel))
{
this.defpackDTO.getElem().add(elem);
}
}
}
private void AssignElemEscursionFromSelection()
{
for(int i=0;i<selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(selectedEscursions[i]);
}
}
public void Search(){
String s=defpackDTO.getLocation();
System.out.print("luogo scelto "+s);
this.setElelis(this.elemMgr.getAllElementsByLocation(s));
for(ElementDTO e:elelis)
{
System.out.print("aggiungo volo "+e.getName());
if(e.getType().equals("Flight"))
{
this.getElelisfly().add(e);
System.out.print("aggiungo volo "+e.getName());
}
}
this.setFlag(true);
}
public ArrayList<ElementDTO> getElelis() {
return elelis;
}
public void setElelis(ArrayList<ElementDTO> elelis) {
this.elelis = elelis;
}
public ArrayList<String> getAvailableLocations() {
return availableLocations;
}
public void setAvailableLocations(ArrayList<String> availableLocations) {
this.availableLocations = availableLocations;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public boolean isFlagdopo() {
return flagdopo;
}
public void setFlagdopo(boolean flagdopo) {
this.flagdopo = flagdopo;
}
public ElementDTO getFlyElem() {
return flyElem;
}
public void setFlyElem(ElementDTO flyElem) {
this.flyElem = flyElem;
}
}
Yes , it is possible to update multiple components in single command button.
<p:commandButton value="Add" update="regGrid ,anothercomponent,anothercomponent2" />
I'm trying to get my richfaces datatable to have sortable headers. I've basically followed the code here: http://richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=dataTable&sample=tableSorting&skin=blueSky
My headers have links, and when I click them, you can see in the firebug console that a post request is happening. After it's done processing, nothing happens to the table.
Also, I have some jquery code that highlights a row when your mouse is hovered over it. Once you click one of the headers, the row highlighting doesn't happen anymore.
Here is my code.
<h:form>
<rich:dataTable value="#{protocolDetail.details.protocolEvents}" var="detail" id="table" rows="20" rowClasses="odd, even" styleClass="stable">
<rich:column sortBy="#{detail.date}">
<f:facet name="header">
<a4j:commandLink value="Date" render="table" action="#{protocolDetail.sortByDate}" />
</f:facet>
<f:facet name="footer">
<a4j:commandLink value="Date" render="table" action="#{protocolDetail.sortByDate}" />
</f:facet>
<h:outputText value="#{detail.date}" />
</rich:column>
<rich:column sortBy="#{detail.description}">
<f:facet name="header">
<a4j:commandLink value="Description" render="table" action="#{protocolDetail.sortByDescription}" />
</f:facet>
<f:facet name="footer">
<a4j:commandLink value="Description" render="table" action="#{protocolDetail.sortByDescription}" />
</f:facet>
<h:outputText value="#{detail.description}" />
</rich:column>
<rich:column sortBy="#{detail.comment}">
<f:facet name="header">
<a4j:commandLink value="Comment" render="table" action="#{protocolDetail.sortByComments}" />
</f:facet>
<f:facet name="footer">
<a4j:commandLink value="Comment" render="table" action="#{protocolDetail.sortByComments}" />
</f:facet>
<h:outputText value="#{detail.comment}" />
</rich:column>
</rich:dataTable>
</h:form>
<rich:jQuery selector=".stable tr" event="mouseover" query="jQuery(this).addClass('active')" />
<rich:jQuery selector=".stable tr" event="mouseout" query="jQuery(this).removeClass('active')" />
bean:
#ManagedBean(name = "protocolDetail")
#SessionScoped
public class ProtocolDetailBacker extends BaseObject {
private String protocol = "";
private int studyNumber;
// private ArrayList<ProtocolDetailBean> details;
private ProtocolDetailBean details = new ProtocolDetailBean();
ProtocolDAO dao = new ProtocolDAO();
private SortOrder dateOrder = SortOrder.UNSORTED;
private SortOrder descriptionOrder = SortOrder.UNSORTED;
private SortOrder commentsOrder = SortOrder.UNSORTED;
public ProtocolDetailBacker() {
FacesContext context = FacesContext.getCurrentInstance();
String[] values = context.getExternalContext().getRequestParameterValuesMap().get("protocol");
setProtocol(values[0]);
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public ProtocolDetailBean getDetails() {
try {
studyNumber = dao.getStudyNumber(getProtocol());
details.setProtocolNumber(getProtocol());
details.setStudyChair(dao.getStudyChair(studyNumber));
details.setShortDesc(dao.getShortDescription(studyNumber));
details.setLongDesc(dao.getLongDescription(studyNumber));
details.setPdc(dao.getPDC(studyNumber));
details.setProtocolEvents(dao.getProtocolEventDetails(getProtocol()));
System.out.println("");
} catch (SQLException e) {
e.printStackTrace();
}
return details;
}
public void setDetails(ProtocolDetailBean details) {
this.details = details;
}
public int getStudyNumber() {
return studyNumber;
}
public void setStudyNumber(int studyNumber) {
this.studyNumber = studyNumber;
}
public SortOrder getDateOrder() {
return dateOrder;
}
public void setDateOrder(SortOrder dateOrder) {
this.dateOrder = dateOrder;
}
public SortOrder getDescriptionOrder() {
return descriptionOrder;
}
public void setDescriptionOrder(SortOrder descriptionOrder) {
this.descriptionOrder = descriptionOrder;
}
public SortOrder getCommentsOrder() {
return commentsOrder;
}
public void setCommentsOrder(SortOrder commentsOrder) {
this.commentsOrder = commentsOrder;
}
public void sortByDate() {
descriptionOrder = SortOrder.UNSORTED;
commentsOrder = SortOrder.UNSORTED;
System.out.println("dateOrder = "+dateOrder);
if(dateOrder.equals(SortOrder.ASCENDING)) {
setDateOrder(SortOrder.DESCENDING);
System.out.println("dateOrder now = "+dateOrder);
} else if(dateOrder.equals(SortOrder.DESCENDING)) {
setDateOrder(SortOrder.ASCENDING);
System.out.println("dateOrder now = "+dateOrder);
} else {
setDateOrder(SortOrder.ASCENDING);
System.out.println("else dateOrder now = "+dateOrder);
}
}
public void sortByDescription() {
dateOrder = SortOrder.UNSORTED;
commentsOrder = SortOrder.UNSORTED;
System.out.println("dateOrder = "+dateOrder);
if(descriptionOrder.equals(SortOrder.ASCENDING)) {
setDescriptionOrder(SortOrder.DESCENDING);
System.out.println("dateOrder now = "+dateOrder);
} else if(descriptionOrder.equals(SortOrder.DESCENDING)) {
setDescriptionOrder(SortOrder.ASCENDING);
System.out.println("dateOrder now = "+dateOrder);
} else {
setDescriptionOrder(SortOrder.ASCENDING);
System.out.println("else dateOrder now = "+dateOrder);
}
}
public void sortByComments() {
descriptionOrder = SortOrder.UNSORTED;
commentsOrder = SortOrder.UNSORTED;
System.out.println("dateOrder = "+dateOrder);
if(commentsOrder.equals(SortOrder.ASCENDING)) {
setCommentsOrder(SortOrder.DESCENDING);
System.out.println("dateOrder now = "+dateOrder);
} else if(commentsOrder.equals(SortOrder.DESCENDING)) {
setCommentsOrder(SortOrder.ASCENDING);
System.out.println("dateOrder now = "+dateOrder);
} else {
setCommentsOrder(SortOrder.ASCENDING);
System.out.println("else dateOrder now = "+dateOrder);
}
}
}
Sorting your table recreates the rows. Therefor the onmouseover and onmouseout events are no more bound to your rows after sorting.
Luckily jQuery can handle this by creating a live handler. Live-Handlers will also trigger to rows, that are added after the execution of the jQuery-call.
The following works for me:
<rich:jQuery selector=".stable tr" query="live('mouseover mouseout', function(event) {
if ( event.type == 'mouseover' ) {
jQuery(this).addClass('active-row');
} else {
jQuery(this).removeClass('active-row');
}});"/>
I too had the same problem was working with the sample code given in richfaces demo , still same issue
I added f:ajax to the a:commandlink now the sort is getting properly updated
<a4j:commandLink execute="#this" value="Vendor"
render="carstable" action="#{carsSortingBean.sort}">
<f:param name="sortProperty" value="vendor" />
<f:ajax render="carstable" />
</a4j:commandLink>
In case anyone is still looking for this answer, If you're using RichFaces 4.0 and JSF 2, try setting JSF's partial state saving to true in your web.xml as seen below:
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>true</param-value>
</context-param>