I'm trying to update a value of a line edited on the datatable (editable = true, row edition). But I always keep getting the old value through the listener. Can you pls tell me where's my mistake? tks..
Here is the code:
<?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:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="_template.xhtml">
<ui:define name="conteudo">
<h:form id="certificacao" >
<p:messages globalOnly="false" showSummary="true" showDetail="true" />
<p:growl id="messages" autoUpdate = "true"/>
<p:fieldset legend="Dados da Certificação">
<h:panelGrid columns="3" >
<p:outputLabel value="Nome da Certificação:" for="nomeCertificacao" style="font-weight:bold"/>
<p:inputText id="nomeCertificacao" value="#{certificacaoBean.certificacao.nomeCertificacao}"
required="true" requiredMessage="Nome da certificação não preenchido" >
</p:inputText>
<br/>
<h:outputLabel value="Descrição da Certificação:" for="descCertificacao" style="font-weight:bold"/>
<p:inputText id="descCertificacao" value="#{certificacaoBean.certificacao.descCertificacao}">
</p:inputText>
<br/>
<p:commandButton value="Gravar" action="#{certificacaoBean.gravar}" icon="fa fa-fw fa-save"
process="#this certificacao" update="#form certificacao" />
<br/>
</h:panelGrid>
</p:fieldset>
<p:dataTable
value="#{certificacaoBean.certificacoes}"
var="certificacao"
id="tabelaCertificacoes"
emptyMessage="Nenhuma certificação cadastrada"
editable="true"
style="margin-bottom:0px"
filteredValue="#{certificacaoBean.certificacaoSelecionada}"
widgetVar="tabelaCertificacoes">
<p:ajax event="rowEdit" listener="#{certificacaoBean.onRowEdit}" update=":certificacao:messages"/>
<p:ajax event="rowEditCancel" listener="#{certificacaoBean.onRowCancel}" update=":certificacao:messages" />
<p:column
headerText="Certificação"
filterBy="#{certificacao.nomeCertificacao}"
filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output">
<div align="center">
<h:outputText value="#{certificacao.nomeCertificacao}" />
</div>
</f:facet>
<f:facet name="input">
<p:inputText value="#{certificacao.nomeCertificacao}" style="width:100%" label="Certificação"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Descrição" filterBy="#{certificacao.descCertificacao}" filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{certificacao.descCertificacao}" /></f:facet>
<f:facet name="input"><p:inputText value="#{certificacao.descCertificacao}" style="width:100%" label="Descrição"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:3px">
<p:rowEditor />
</p:column>
<p:column style="width:3px">
<f:facet name="header">
<h:outputText value="" style="width:3px"/>
</f:facet>
<p:commandButton
action="#{certificacaoBean.removeCertificacao(certificacao)}"
icon="ui-icon-close"
title="Remover Certificação"
update="tabelaCertificacoes"
process="#this" >
<f:setPropertyActionListener
target="#{certificacaoBean.certificacaoSelecionada}"
value="#{certificacao}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</ui:define>
The bean part:
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import br.com.dao.DAO;
import br.com.model.Certificacao;
#ManagedBean(name="certificacaoBean")
#ViewScoped
public class CertificacaoBean implements Serializable {
private static final long serialVersionUID = 1L;
private Certificacao certificacao = new Certificacao();
public void setCertificacao(Certificacao certificacao) {
this.certificacao = certificacao;
}
private Certificacao certificacaoSelecionada;
public Certificacao getCertificacao() {
return certificacao;
}
public Certificacao getCertificacaoSelecionada() {
return certificacaoSelecionada;
}
public void setCertificacaoSelecionada(Certificacao certificacaoSelecionada) {
this.certificacaoSelecionada = certificacaoSelecionada;
}
public void removeCertificacao(Certificacao certificacao) {
new DAO<Certificacao>(Certificacao.class).remove(certificacaoSelecionada);
FacesMessage msg = new FacesMessage("Certificação excluída","");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<Certificacao> getCertificacoes() {
return new DAO<Certificacao>(Certificacao.class).listaTodos();
}
public void gravar() {
System.out.println("Gravando Certificação " + this.certificacao.getNomeCertificacao());
if (certificacao.getNomeCertificacao().isEmpty()) {
FacesContext.getCurrentInstance().addMessage ("nomeCertificacao",
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"O nome da certificação deve ser preenchido.", "O nome da certificação deve ser preenchido."));
return;
}
new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
this.certificacao = new Certificacao();
}
// Inicio Editor na Tabela
public void onRowEdit(RowEditEvent event) {
System.out.println("Passando no DAO retorno event Cod: " + ((((Certificacao) event.getObject()).getCodigoCertificacao())));
System.out.println("Passando no DAO retorno event Name: " + ((((Certificacao) event.getObject()).getNomeCertificacao())));
System.out.println("Passando no DAO retorno object: " + ((((Certificacao) event.getObject()))));
System.out.println("DAO evento " + event);
//new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
//Problema AQUI
new DAO<Certificacao>(Certificacao.class).atualiza((((Certificacao) event.getObject())));
this.certificacao = new Certificacao();
FacesMessage msg = new FacesMessage("Certificação editada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edição cancelada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
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);
}
}
}
And the dao:
package br.com.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
public class DAO<T> {
private final Class<T> classe;
public DAO(Class<T> classe) {
this.classe = classe;
}
public void adiciona(T t) {
// consegue a entity manager
EntityManager em = new JPAUtil().getEntityManager();
// abre transacao
em.getTransaction().begin();
// persiste o objeto
em.persist(t);
// commita a transacao
em.getTransaction().commit();
// fecha a entity manager
em.close();
}
public void remove(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.remove(em.merge(t));
em.getTransaction().commit();
em.close();
}
public void atualiza(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.merge(t);
em.getTransaction().commit();
em.close();
}
public List<T> listaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).getResultList();
em.close();
return lista;
}
public T buscaPorId(Integer id) {
EntityManager em = new JPAUtil().getEntityManager();
T instancia = em.find(classe, id);
em.close();
return instancia;
}
public int contaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
long result = (Long) em.createQuery("select count(n) from certificacao n")
.getSingleResult();
em.close();
return (int) result;
}
public List<T> listaTodosPaginada(int firstResult, int maxResults) {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).setFirstResult(firstResult)
.setMaxResults(maxResults).getResultList();
em.close();
return lista;
}
}
In your code, You only update the message'id not the datatable's id. Try to update the form in the "update" attribute of ajax when edit the row.
Related
Need some help to know if my solution is valid or not.
I have a primefaces datatable with single row selection, and I need to add a multiple selection checkbox column... My idea is to switch selection mode clicking on one button, that switch the selection mode from single to multiple and vice versa....
<pf:dataTable
value="${bean.notifications}"
var="notif"
selection="#{bean.isMultiple() ? consulterCorbeilleBean.selectedNotifs : consulterCorbeilleBean.selectedNotif}"
selectionMode="#{not bean.isMultiple() ? 'single' : ''}"
rowKey="${notification.cle.idNotification}">
<pf:ajax event="rowSelect" disabled="${bean.isMultiple()}"
listener="${bean.function()}" update=":table:notificationTable"
oncomplete="stopPropagationClick()" />
<pf:column selectionMode="multiple" rendered="#{bean.isMultiple()}"/>
</pf:dataTable>
I have a problem with the selection binding. I have this error :
Illegal Syntax for Set Operation:
javax.el.PropertyNotWritableException: /index.xhtml #114,50
selection="#{bean.isMultiple() ? bean.selectedNotifs :
bean.selectedNotif}"
Any idea to workaround ? I use Primefaces 3.2.
Best Regards and thanks for your help :)
You can't use dynamic setter values on the selection.
I would rethink the design if i were you, but if you really need both single and multiple selection options on the same table, you could use 2 datatables and render only 1 of them at a time, and switch between them with a button click.
If you really need it, then you can try this work example
View
<h:form id="form">
<p:growl id="msgs" showDetail="true" for="basicDT" />
<p:inputSwitch value="#{dtSelectionView.multiple}">
<p:ajax listener="#{dtSelectionView.addMessage}" update="basicDT, msgs" />
</p:inputSwitch>
<p:dataTable
id="basicDT"
var="car"
value="#{dtSelectionView.cars1}"
rowStyleClass="#{dtSelectionView.checkSelection(car)? 'ui-state-highlight':''}"
>
<f:facet name="header">
DoubleSelect
</f:facet>
<p:column style="width:32px">
<p:commandButton update="basicDT,:form:msgs,:form:carDetail,:form:multiCarDetail" icon="ui-icon-check" actionListener="#{dtSelectionView.addSelection(car)}" />
</p:column>
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
<p:dialog header="Car Info" widgetVar="carDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false" closeOnEscape="true">
<p:outputPanel id="carDetail" style="text-align:center;">
<p:panelGrid columns="2" rendered="#{not empty dtSelectionView.selectedCar}" columnClasses="label,value">
<h:outputText value="Id:" />
<h:outputText value="#{dtSelectionView.selectedCar.id}" />
<h:outputText value="Year" />
<h:outputText value="#{dtSelectionView.selectedCar.year}" />
<h:outputText value="Color:" />
<h:outputText value="#{dtSelectionView.selectedCar.color}" style="color:#{dtSelectionView.selectedCar.color}"/>
<h:outputText value="Price" />
<h:outputText value="$#{dtSelectionView.selectedCar.price}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
<p:dialog header="Selected Cars" widgetVar="multiCarDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false" width="200">
<p:outputPanel id="multiCarDetail" style="text-align:center;">
<ui:repeat value="#{dtSelectionView.selectedCars}" var="car">
<h:outputText value="#{car.id} - #{car.brand}" style="display:block"/>
</ui:repeat>
</p:outputPanel>
</p:dialog>
</h:form>
Model
import java.io.Serializable;
public class Car implements Serializable{
private String Id;
private String Brand;
private int Year;
private String Color;
private int Price;
private boolean SoldState;
public Car(String id, String brand, int year, String color, int price,
boolean soldState) {
super();
Id = id;
Brand = brand;
Year = year;
Color = color;
Price = price;
SoldState = soldState;
}
#Override
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof Car)) return false;
Car other = (Car) o;
if(! this.Id.equals(other.Id)) return false;
if(! this.Brand.equals(other.Brand)) return false;
if(this.Year != other.Year) return false;
if(! this.Color.equals(other.Color)) return false;
if(this.Price != other.Price) return false;
if(this.SoldState != other.SoldState) return false;
return true;
}
#Override
public int hashCode(){
return (int) Id.hashCode() *
Brand.hashCode() *
Year *
Color.hashCode() *
Price *
(SoldState ? 31 : 32)
;
}
/** getters/setters */
}
Bean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
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.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean(name="dtSelectionView")
#ViewScoped
public class SelectionView implements Serializable {
private List<Car> cars1;
private Car selectedCar;
private List<Car> selectedCars;
private boolean multiple= false;
#ManagedProperty("#{carService}")
private CarService service;
#PostConstruct
public void init() {
cars1 = service.createCars(10);/** random generated List. See PF showcase, datatable examples*/
selectedCars = new ArrayList<Car>();
}
public boolean checkSelection(Car car){
if(isMultiple())
return selectedCars.contains(car) ? true : false;
else
return car.equals(selectedCar) ? true : false;
}
public void addSelection(Car car){
String summary = "Car was ";
if(isMultiple())
if(selectedCars.contains(car)){
selectedCars.remove(car);
summary += "removed from list.";
}
else{
selectedCars.add(car);
summary += "added to list.";
RequestContext.getCurrentInstance().execute("PF('multiCarDialog').show();");
}
else
if(car.equals(selectedCar)){
selectedCar = null;
summary += "unselected.";
}
else{
selectedCar = car;
summary += "selected.";
RequestContext.getCurrentInstance().execute("PF('carDialog').show();");
}
FacesContext.getCurrentInstance().addMessage("basicDT", new FacesMessage(summary));
}
public void setService(CarService service) {
this.service = service;
}
public Car getSelectedCar() {
return selectedCar;
}
public List<Car> getSelectedCars() {
return selectedCars;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void addMessage() {
selectedCar = null;
selectedCars = new ArrayList<Car>();
String summary = multiple ? "Checked" : "Unchecked";
FacesContext.getCurrentInstance().addMessage("basicDT", new FacesMessage(summary));
}
public List<Car> getCars1() {
return cars1;
}
public void setCars1(List<Car> cars1) {
this.cars1 = cars1;
}
public CarService getService() {
return service;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
Hope You'll in right direction.
I am working on richfaces4,
when i am trying to edit details from a popup panel,i am not able to save/update the edited details into my database.can anybody help me to solve this.
My XHTML Page is as follows:
<!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:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:t="http://myfaces.apache.org/tomahawk">
<h:head>
</h:head>
<h:body>
<h:form id="dboperatorform">
<t:saveState value="#{dBOperator.empList}"></t:saveState>
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<t:saveState value="#{dBOperator.employee}"></t:saveState>
<rich:panel style="width:1345px">
<f:facet name="header">
<h:outputText value="Search Panel" />
</f:facet>
<h:panelGrid id="searchPanel" columns="6">
<h:column>
<h:outputLabel value="First Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.first_Name}" />
</h:column>
<h:column>
<h:outputLabel value="Last Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.last_name}" />
</h:column>
<h:column>
<a4j:commandButton value="Search" action="#{dBOperator.search}"
render="richtable">
</a4j:commandButton>
</h:column>
<h:column>
</h:column>
</h:panelGrid>
</rich:panel>
<br />
<a4j:commandButton value="Add" action="#{dBOperator.editdetails}"
execute="#this" style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="false"></f:setPropertyActionListener>
</a4j:commandButton>
<p></p>
<rich:dataTable value="#{dBOperator.employees}" var="emp"
id="richtable" cellpadding="0" cellspacing="0" style="width:1349px"
reRender="richtable" iterationStatusVar="it"
noDataLabel="No Records Found!" rows="5">
<rich:column>
<f:facet name="header">#</f:facet>
<h:outputText value="#{it.index}" />
</rich:column>
<rich:column>
<f:facet name="header">
<a4j:commandLink value="First Name"
action="#{dBOperator.sortByFirstName}" render="richtable"></a4j:commandLink>
</f:facet>
<h:outputText value="#{emp.first_Name}" />
</rich:column>
<rich:column>
<f:facet name="header">Last Name</f:facet>
<h:outputText value="#{emp.last_name}" />
</rich:column>
<rich:column>
<f:facet name="header">Edit</f:facet>
<a4j:commandButton image="images/edit.png"
action="#{dBOperator.editdetails}" execute="#this"
style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.rowNum}"
value="#{it.index}"></f:setPropertyActionListener>
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="true"></f:setPropertyActionListener>
</a4j:commandButton>
</rich:column>
<f:facet name="footer">
<rich:dataScroller for="richtable" align="right"
status="ajaxProcessIcon" renderIfSinglePage="false" fastStep="5"
fastControls="auto" />
</f:facet>
</rich:dataTable>
<rich:popupPanel id="popup1" minHeight="300"
minWidth="300">
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<f:facet name="header">
<h:outputText value="Simple popup panel" />
</f:facet>
<f:facet name="controls">
<h:outputLink
onclick="#{rich:component('popup1')}.hide(); return false;"
reRender="richtable">X</h:outputLink>
</f:facet>
<rich:toolbar itemSeparator="line" width="100%" id="qawq">
<rich:toolbarGroup location="left">
<h:outputText
value="#{dBOperator.edit?'Employee Edit':'Employee Add'}" />
</rich:toolbarGroup>
</rich:toolbar>
<h:panelGrid id="CancelGrid" columns="2" width="100%">
<rich:column width="30%" style="border:none;">
<h:outputText value="First Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.first_Name}"
style="width:100%" id="abbr" />
</rich:column>
<rich:column width="30%" style="border:none;">
<h:outputText value="Last Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.last_name}"
style="width:100%" id="abbr1" />
</rich:column>
</h:panelGrid>
<a4j:commandButton value="#{dBOperator.edit?'Edit':'Save'}"
action="#{dBOperator.savedetails}"
oncomplete="#{rich:component('popup1')}.hide();"
onclick="validateFields();"></a4j:commandButton>
</rich:popupPanel>
<script type="text/javascript">
function validateFields() {
alert('came inside validateFields');
var fn=document.getElementById('dboperatorform:abbr');
alert('fn '+fn.value);
var ln=document.getElementById('dboperatorform:abbr1');
alert('ln '+ln.value);
}
</script>
</h:form>
</h:body>
</html>
My Bean Class is as follows
package com.richfaces.db;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.management.MBeanServer;
import javax.swing.SortOrder;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.comparator.NameComparator;
import com.comparator.NameCompartor1;
import com.richfaces.Employee;
public class DBOperator {
String id;
String first_Name;
String last_name;
String fName;
String lName;
Employee employee;
int rowNum;
boolean edit;
Boolean search=Boolean.FALSE;
Boolean status = Boolean.FALSE;
List<Employee> list = new ArrayList<Employee>();
List<Employee> empList = new ArrayList<Employee>();
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public List<Employee> getEmployees() {
System.out.println("hghhghhhhh");
String sql2="";
Query query = null;
String sql1 = "from Employee as emp where id is not null ";
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
sess.beginTransaction();
if(status==false && search==false) {
System.out.println("Normal Query +++++++++++++++++++++++ " + sql1);
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==true) {
System.out.println("came inside when search and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==false && search==true) {
System.out.println("came inside when search is true and status is false");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==false) {
System.out.println("came inside when search is false and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}
list = query.list();
/*if (status) {
Collections.sort(list, new NameComparator());
} else {
Collections.sort(list, new NameCompartor1());
}*/
System.out.println(list.size());
this.empList = list;
return list;
}
public String createCriteriaQuery(String query) {
StringBuffer sb = new StringBuffer(query);
if (getFirst_Name() != null && !(getFirst_Name().equals(""))) {
sb.append(" and emp.first_Name='" + first_Name + "'");
}
if (getLast_name() != null && !(getLast_name().equals(""))) {
sb.append(" and emp.last_name='" + last_name + "'");
}
if(this.status) {
sb.append(" order by emp.first_Name desc");
}else {
sb.append(" order by emp.first_Name");
}
System.out.println(sb.toString());
return sb.toString();
}
public void editdetails() {
if (edit) {
System.out.println("rownum is " + rowNum);
System.out.println(empList.size());
employee = (Employee) empList.get((rowNum));
System.out.println(employee.getFirst_Name() + "\t"
+ employee.getLast_name() + "\t" + employee.getId());
System.out.println("end of edit details method");
} else {
employee = new Employee();
}
}
public List<Employee> getEmpList() {
return empList;
}
public void setEmpList(List<Employee> empList) {
this.empList = empList;
}
public void savedetails() {
System.out.println("came into savedetails");
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
if(this.edit) {
System.out.println("EMPLOYEE DETAILS in IF "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
System.out.println("came inside if when edit is true");
sess.update(employee);
}else {
System.out.println("came inside else when edit is false");
System.out.println("EMPLOYEE DETAILS in ELSE "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
sess.save(employee);
}
}
public void search() {
System.out.println("came into search method");
search = true;
}
public void refreshData(ActionEvent ae) {
System.out.println("came into refreshdata");
getEmployees();
}
public void sortByFirstName() {
System.out.println("came inside sortByFirstName");
if (!status) {
status = Boolean.TRUE;
} else {
status = Boolean.FALSE;
}
//status=Boolean.TRUE;
getEmployees();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
My Entity class is as follows:
package com.richfaces;
import java.io.Serializable;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String id;
String first_Name;
String last_name;
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
System.out.println("came inside setter method of firstname");
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
System.out.println("came inside setter method of lastname");
this.last_name = last_name;
}
}
if your exact problem is not seeing #{dBOperator.savedetails} action triggered:
i couldn't figure out the root cause yet, but this problem should be fixed by adding modal="true" to the rich:popupPanel attributes and moving validateFields() function into the popup panel. i faced this problem many times and saw it working properly on different popup components, including this one.
I am not able to get the required data in rich popup panel when I click on edit link. Can anybody help me in resolving it.
When I am trying to edit row details, I am not able to get the required data in their respective fields for the first time, but surprisingly when i refresh my page and do the same procedure, I got the data in their respective fields.
I want to get the required data on click of edit link for the first time.
So, can anybody help me to resolve it.
My 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:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:t="http://myfaces.apache.org/tomahawk">
<h:head>
</h:head>
<h:body>
<h:form id="dboperatorform">
<t:saveState value="#{dBOperator.empList}"></t:saveState>
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<t:saveState value="#{dBOperator.employee}"></t:saveState>
<rich:panel style="width:1345px">
<f:facet name="header">
<h:outputText value="Search Panel" />
</f:facet>
<h:panelGrid id="searchPanel" columns="6">
<h:column>
<h:outputLabel value="First Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.first_Name}" />
</h:column>
<h:column>
<h:outputLabel value="Last Name:" />
</h:column>
<h:column>
<h:inputText value="#{dBOperator.last_name}" />
</h:column>
<h:column>
<a4j:commandButton value="Search" action="#{dBOperator.search}"
render="richtable">
</a4j:commandButton>
</h:column>
<h:column>
</h:column>
</h:panelGrid>
</rich:panel>
<br />
<a4j:commandButton value="Add" action="#{dBOperator.editdetails}"
execute="#this" style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="false"></f:setPropertyActionListener>
</a4j:commandButton>
<p></p>
<rich:dataTable value="#{dBOperator.employees}" var="emp"
id="richtable" cellpadding="0" cellspacing="0" style="width:1349px"
reRender="richtable" iterationStatusVar="it"
noDataLabel="No Records Found!" rows="5">
<rich:column>
<f:facet name="header">#</f:facet>
<h:outputText value="#{it.index}" />
</rich:column>
<rich:column>
<f:facet name="header">
<a4j:commandLink value="First Name"
action="#{dBOperator.sortByFirstName}" render="richtable"></a4j:commandLink>
</f:facet>
<h:outputText value="#{emp.first_Name}" />
</rich:column>
<rich:column>
<f:facet name="header">Last Name</f:facet>
<h:outputText value="#{emp.last_name}" />
</rich:column>
<rich:column>
<f:facet name="header">Edit</f:facet>
<a4j:commandButton image="images/edit.png"
action="#{dBOperator.editdetails}" execute="#this"
style="width:30px;height:30px;"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable popup1">
<f:setPropertyActionListener target="#{dBOperator.rowNum}"
value="#{it.index}"></f:setPropertyActionListener>
<f:setPropertyActionListener target="#{dBOperator.edit}"
value="true"></f:setPropertyActionListener>
</a4j:commandButton>
</rich:column>
<f:facet name="footer">
<rich:dataScroller for="richtable" align="right"
status="ajaxProcessIcon" renderIfSinglePage="false" fastStep="5"
fastControls="auto" />
</f:facet>
</rich:dataTable>
<rich:popupPanel id="popup1" minHeight="300"
minWidth="300">
<t:saveState value="#{dBOperator.edit}"></t:saveState>
<t:saveState value="#{dBOperator.rowNum}"></t:saveState>
<f:facet name="header">
<h:outputText value="Simple popup panel" />
</f:facet>
<f:facet name="controls">
<h:outputLink
onclick="#{rich:component('popup1')}.hide(); return false;"
reRender="richtable">X</h:outputLink>
</f:facet>
<rich:toolbar itemSeparator="line" width="100%" id="qawq">
<rich:toolbarGroup location="left">
<h:outputText
value="#{dBOperator.edit?'Employee Edit':'Employee Add'}" />
</rich:toolbarGroup>
</rich:toolbar>
<h:panelGrid id="CancelGrid" columns="2" width="100%">
<rich:column width="30%" style="border:none;">
<h:outputText value="First Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.first_Name}"
style="width:100%" id="abbr" />
</rich:column>
<rich:column width="30%" style="border:none;">
<h:outputText value="Last Name" style="font-weight: bold;" />
<font class="star" color="red">*</font>
</rich:column>
<rich:column width="70%" style="border:none;">
<h:inputText value="#{dBOperator.employee.last_name}"
style="width:100%" id="abbr1" />
</rich:column>
</h:panelGrid>
<a4j:commandButton value="#{dBOperator.edit?'Edit':'Save'}"
action="#{dBOperator.savedetails}"
oncomplete="#{rich:component('popup1')}.hide();"
onclick="validateFields();"></a4j:commandButton>
</rich:popupPanel>
<script type="text/javascript">
function validateFields() {
alert('came inside validateFields');
var fn=document.getElementById('dboperatorform:abbr');
alert('fn '+fn.value);
var ln=document.getElementById('dboperatorform:abbr1');
alert('ln '+ln.value);
}
</script>
</h:form>
</h:body>
</html>
My Bean Class code
package com.richfaces.db;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.management.MBeanServer;
import javax.swing.SortOrder;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.comparator.NameComparator;
import com.comparator.NameCompartor1;
import com.richfaces.Employee;
public class DBOperator {
String id;
String first_Name;
String last_name;
String fName;
String lName;
Employee employee;
int rowNum;
boolean edit;
Boolean search=Boolean.FALSE;
Boolean status = Boolean.FALSE;
List<Employee> list = new ArrayList<Employee>();
List<Employee> empList = new ArrayList<Employee>();
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public List<Employee> getEmployees() {
System.out.println("hghhghhhhh");
String sql2="";
Query query = null;
String sql1 = "from Employee as emp where id is not null ";
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
sess.beginTransaction();
if(status==false && search==false) {
System.out.println("Normal Query +++++++++++++++++++++++ " + sql1);
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==true) {
System.out.println("came inside when search and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==false && search==true) {
System.out.println("came inside when search is true and status is false");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}else if(status==true && search==false) {
System.out.println("came inside when search is false and status is true");
String appendedQuery = createCriteriaQuery(sql1);
System.out.println("Appended Query ++++++++++++++++++++++++ "
+ appendedQuery);
query = sess.createQuery(appendedQuery);
}
list = query.list();
/*if (status) {
Collections.sort(list, new NameComparator());
} else {
Collections.sort(list, new NameCompartor1());
}*/
System.out.println(list.size());
this.empList = list;
return list;
}
public String createCriteriaQuery(String query) {
StringBuffer sb = new StringBuffer(query);
if (getFirst_Name() != null && !(getFirst_Name().equals(""))) {
sb.append(" and emp.first_Name='" + first_Name + "'");
}
if (getLast_name() != null && !(getLast_name().equals(""))) {
sb.append(" and emp.last_name='" + last_name + "'");
}
if(this.status) {
sb.append(" order by emp.first_Name desc");
}else {
sb.append(" order by emp.first_Name");
}
System.out.println(sb.toString());
return sb.toString();
}
public void editdetails() {
if (edit) {
System.out.println("rownum is " + rowNum);
System.out.println(empList.size());
employee = (Employee) empList.get((rowNum));
System.out.println(employee.getFirst_Name() + "\t"
+ employee.getLast_name() + "\t" + employee.getId());
System.out.println("end of edit details method");
} else {
employee = new Employee();
}
}
public List<Employee> getEmpList() {
return empList;
}
public void setEmpList(List<Employee> empList) {
this.empList = empList;
}
public void savedetails() {
System.out.println("came into savedetails");
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session sess = sf.openSession();
if(this.edit) {
System.out.println("EMPLOYEE DETAILS in IF "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
System.out.println("came inside if when edit is true");
sess.update(employee);
}else {
System.out.println("came inside else when edit is false");
System.out.println("EMPLOYEE DETAILS in ELSE "+getEmployee().getFirst_Name()+"\t"+getEmployee().getLast_name());
sess.save(employee);
}
}
public void search() {
System.out.println("came into search method");
search = true;
}
public void refreshData(ActionEvent ae) {
System.out.println("came into refreshdata");
getEmployees();
}
public void sortByFirstName() {
System.out.println("came inside sortByFirstName");
if (!status) {
status = Boolean.TRUE;
} else {
status = Boolean.FALSE;
}
//status=Boolean.TRUE;
getEmployees();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
My Entity class code as follows:
package com.richfaces;
import java.io.Serializable;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String id;
String first_Name;
String last_name;
public String getFirst_Name() {
return first_Name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFirst_Name(String first_Name) {
this.first_Name = first_Name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
}
Change a4j:commandButton attributes
<a4j:commandButton value="Edit" action="#{dBOperator.editdetails}" execute="#this"
oncomplete="#{rich:component('popup1')}.show();"
render="richtable, popup1">
<f:setPropertyActionListener target="#{dBOperator.rowNum}" value="#{it.index}" />
</a4j:commandButton>
i am new on prime faces .I have a user with some attribute i have shown the table of user data . Now the requirement is that, on click of particular user row the data associated with that user must be shown on same window under the table please tell the way to do this i m trying to use layout but the problem is how i can get the data on same window .Give me learing site link if possible doing the same thing or tell me the procedure thanks
package com.poc.faces;
import java.util.Collection;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean
#ViewScoped
public class UserManagedBean {
UserService service = new UserService();
private String username;
private String password;
private String searchUser;
private Collection<User> searchUsersResults;
private User selectedUser;
public UserService getService() {
return service;
}
public void setService(UserService service) {
this.service = service;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSearchUser() {
return searchUser;
}
public void setSearchUser(String searchUser) {
this.searchUser = searchUser;
}
public Collection<User> getSearchUsersResults() {
return searchUsersResults = service.getAllUser();
}
public void setSearchUsersResults(Collection<User> searchUsersResults) {
this.searchUsersResults = searchUsersResults;
}
public User getSelectedUser() {
return selectedUser;
}
public String login() {
if ("sas".equalsIgnoreCase(getUsername())
&& "sas".equals(getPassword())) {
return "home";
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage(
"Invalid UserName and Password"));
return "login";
}
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("User Selected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This home.xhtml
where i am getting the tabledata
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<link href="../css/style.css" type="text/css" rel="stylesheet" />
</h:head>
<h:body>
<p:layout style="min-width:400px;min-height:200px;" id="layout">
<p:layoutUnit position="center">
<h:form prependId="false">
<h:panelGroup layout="block" id="left_column"
style="width: 2px; left: 2px; margin-left: 2px">
<center>
<H1>UserData</H1>
<br />
<p:dataTable value="#{userManagedBean.searchUsersResults}"
var="user" pagination="true" rows="5" styleClass="userTable"
headerClass="userTableHeader"
rowClasses="userTableOddRow,userTableEvenRow"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<!-- <p:ajax event="rowSelect" listener="#{userManagedBean.onRowSelect}"
update=":form:display :form:growl" oncomplete="carDialog.show()" />
<p:ajax event="rowUnselect"
listener="#{userManagedBean.onRowUnselect}" update=":form:growl" /> -->
<p:column>
<f:facet name="header">UserId</f:facet>
<h:outputText value="#{user.userId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Username</f:facet>
<h:outputText value="#{user.username}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">EmailId</f:facet>
<h:outputText value=" #{user.emailId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Phone</f:facet>
<h:outputText value=" #{user.phone}"></h:outputText>
</p:column>
</p:dataTable>
</center>
</h:panelGroup>
</h:form>
<p:layoutUnit position="west" resizable="true" size="100"
minSize="40" maxSize="200">
West
</p:layoutUnit>
</p:layout>
</h:body>
</html>
I don't think there is a component of PF called layoutUnit. are you sure it's not layout?
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
primefaces selectOneMenu doesn’t working when it should
my setPropertyActionListener is not setting the corresponding bean property. I need to get the select public after i click the corresponding delete button (cbViewExcluir) which shows a confirm dialog before delete. Below is my xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="./../../resources/templates/baseTemplate.xhtml">
<ui:define name="content">
<f:view id="vRoot">
<p:fieldset legend="Manage publics">
<h:form id="frmPublics">
<!-- Global messages -->
<p:growl id="gMessages" sticky="false" globalOnly="true" />
<!-- Public list on dataTable -->
<p:dataTable id="dtPublics"
value="#{publicBean.lstPublics}"
paginator="true" rows="5"
rowsPerPageTemplate="5,10"
paginatorPosition="bottom"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
var="actual">
<f:facet name="header">
<p:commandButton id="cbViewNew" value="New" type="button" onclick="dlgNew.show();" />
</f:facet>
<!-- Colunas de edição e exclusão -->
<p:column>
<f:facet name="header">
<h:outputLabel value="Edit"/>
</f:facet>
<p:commandButton id="cbViewEdit"
image="ui-icon-pencil"
title="Edit"
update=":frmEdit:pEditPublic"
oncomplete="dlgEdit.show();">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
<h:outputLabel value="Delete"/>
</f:facet>
<p:commandButton id="cbViewDelete" onclick="dlgDelete.show();"
icon="ui-icon-close" title="Delete">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
<h:outputLabel id="olViewPublicName" value="#{actual.publicName}"/>
</p:column>
<p:column>
<f:facet name="header">
Public Type
</f:facet>
<h:outputLabel id="olViewPublicType" value="#{actual.publicType}"/>
</p:column>
</p:dataTable>
</h:form>
<!-- New dialog -->
<p:dialog id="dlgNewPublic" widgetVar="dlgNew" modal="true" header="New Public"
resizable="false">
<h:form id="frmNew">
<p:panel id="pNewPublico">
<p:messages id="mNewMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olNewPublicName" value="Name:" for="itNewPublicName"/>
<p:inputText id="itNewPublicName" value="#{publicBean.name}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olNewPublicType" for="somNewPublicType" value="Public type:"/>
<p:selectOneMenu id="somNewPublicType" value="#{publicBean.publicType}" effect="fade"
converter="#{publicBean.converter}"
required="true" requiredMessage="Enter the public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}" var="actual" itemLabel="#{actual.label}" itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgNew.hide()"/>
<p:commandButton id="cbSaveNew" value="Save"
actionListener="#{publicBean.save}"
oncomplete="handleSave(xhr, status, args);"
update=":frmPublics:dtPublics :frmNew :frmPublics:gMessages"
ajax="true"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
<!-- Delete dialog -->
<p:confirmDialog id="dialogDelete" message="Are you sure?"
header="Delete public" severity="alert"
widgetVar="dlgDelete">
<h:form id="frmDelete">
<p:commandButton id="cbDeleteCancel" value="Cancel" onclick="dlgDelete.hide()" type="button" />
<p:commandButton id="cbDeleteContinue" value="Continue"
update=":frmPublics:dtPublics :frmPublics:gMessages"
oncomplete="dlgDelete.hide()"
actionListener="#{publicBean.delete}"/>
</h:form>
</p:confirmDialog>
<!-- Edit dialog -->
<p:dialog id="dialogEdit" widgetVar="dlgEdit" header="Edit public"
resizable="false" modal="true">
<h:form id="frmEdit">
<p:panel id="pEditPublic">
<p:messages id="mEditMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olEditPublicName" value="Name:" for="itEditPublicName"/>
<p:inputText id="itEditPublicName" value="#{publicBean.selectedPublic.publicName}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olEditPublicType" for="somEditPublicType" value="Public type:"/>
<p:selectOneMenu id="somEditPublicType"
value="#{publicBean.selectedPublic.publicType}"
effect="fade"
converter="#{publicBean.converter}"
required="true"
requiredMessage="Select a public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}"
var="actual"
itemLabel="#{actual.label}"
itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgEdit.hide()"/>
<p:commandButton id="cbEditSave" value="Save"
actionListener="#{publicBean.alter}"
oncomplete="dlgEdit.hide();"
update=":frmPublics :frmEdit"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</p:fieldset>
</f:view>
<!-- Javascript callbacks -->
<script type="text/javascript">
function handleSaved(xhr, status, args){
if(args.saved){
dlgNew.hide();
}
}
function handleEdited(xhr, status, args){
if(args.edited){
dlgEdit.hide();
}
}
</script>
</ui:define>
And my bean is as follows:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.siseventos.managed;
import br.siseventos.dao.da.PublicoDAO;
import br.siseventos.dao.da.TipoPublicoDAO;
import br.siseventos.model.TbPublico;
import br.siseventos.model.TdTipoPublico;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "publicoBean")
#SessionScoped
public class PublicoBean {
// Campos
private TipoPublicoDAO daoTipoPublico = null;
private PublicoDAO daoPublico = null;
private String nome;
private List<SelectItem> lstMenuTipoPublico = new ArrayList<SelectItem>();
private TdTipoPublico tipoPublicoSelecionado = null;
private List<TbPublico> lstDataTablePublico = null;
private TbPublico publicoSelecionado;
// Util
private int maximoLinhasTablePublico = 5;
private boolean mostrarMsg = false;
// Construtor
public PublicoBean() {
// Inicializando as daos
daoPublico = new PublicoDAO();
daoTipoPublico = new TipoPublicoDAO();
// Carregando o datatable de publicos
lstDataTablePublico = daoPublico.consultarTodos();
// Carregando o menu de tipos de público
List<TdTipoPublico> l = getDaoTipoPublico().consultarTodos();
Iterator<TdTipoPublico> i = l.iterator();
while (i.hasNext()) {
TdTipoPublico atual = (TdTipoPublico) i.next();
lstMenuTipoPublico.add(new SelectItem(atual, atual.getNmeTipoPublico()));
}
}
public TipoPublicoDAO getDaoTipoPublico() {
return daoTipoPublico;
}
public void setDaoTipoPublico(TipoPublicoDAO daoTipoPublico) {
this.daoTipoPublico = daoTipoPublico;
}
public PublicoDAO getDaoPublico() {
return daoPublico;
}
public void setDaoPublico(PublicoDAO daoPublico) {
this.daoPublico = daoPublico;
}
// Getters e Setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<SelectItem> getLstMenuTipoPublico() {
return lstMenuTipoPublico;
}
public void setLstMenuTipoPublico(List<SelectItem> lstMenuTipoPublico) {
this.lstMenuTipoPublico = lstMenuTipoPublico;
}
public TdTipoPublico getTipoPublicoSelecionado() {
return tipoPublicoSelecionado;
}
public void setTipoPublicoSelecionado(TdTipoPublico tipoPublicoSelecionado) {
this.tipoPublicoSelecionado = tipoPublicoSelecionado;
}
public List<TbPublico> getLstDataTablePublico() {
return lstDataTablePublico;
}
public void setLstDataTablePublico(List<TbPublico> lstDataTablePublico) {
this.lstDataTablePublico = lstDataTablePublico;
}
public int getMaximoLinhasTablePublico() {
return maximoLinhasTablePublico;
}
public void setMaximoLinhasTablePublico(int maximoLinhasTablePublico) {
this.maximoLinhasTablePublico = maximoLinhasTablePublico;
}
public boolean isMostrarMsg() {
return mostrarMsg;
}
public void setMostrarMsg(boolean mostrarMsg) {
this.mostrarMsg = mostrarMsg;
}
public TbPublico getPublicoSelecionado() {
return publicoSelecionado;
}
public void setPublicoSelecionado(TbPublico publicoSelecionado) {
this.publicoSelecionado = publicoSelecionado;
}
// Actions e listeners
public void cadastrarPublico(ActionEvent ex) {
FacesContext contexto = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage();
try {
TbPublico p = new TbPublico();
p.setNmePublico(getNome());
p.setTdTipoPublico(getTipoPublicoSelecionado());
getDaoPublico().incluir(p);
// Carregar a lista de publicos novamente
lstDataTablePublico = getDaoPublico().consultarTodos();
// Mostrando msg de sucesso!
msg.setSummary("Público cadastrado com sucesso!");
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
// Invocando script no cliente
RequestContext rc = RequestContext.getCurrentInstance();
rc.addCallbackParam("salvo", true);
} catch (Exception e) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}
}
public void excluirPublico(ActionEvent e) {
FacesMessage msg = new FacesMessage();
FacesContext contexto = FacesContext.getCurrentInstance();
// Mostrando msg de sucesso!
msg.setSummary(publicoSelecionado.getNmePublico());
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
/*try {
// Excluindo o publico selecionado
daoPublico.excluir(getPublicoSelecionado().getIdtPublico());
} catch (Exception ex) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}*/
}
public void alterarPublico() {
FacesMessage msg = new FacesMessage("Publico alterado!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
// Converters
public Converter getConversor() {
return new Converter() {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Transformar string em objeto
TdTipoPublico r = null;
try {
r = getDaoTipoPublico().consultarPorIdt(Integer.parseInt(value));
} catch (NumberFormatException e) {
}
return r;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Transformar objeto em string
String r = null;
if (value instanceof TdTipoPublico) {
r = ((TdTipoPublico) value).getIdtTipoPublico().toString();
}
return r;
}
};
}
}
There is something i'm doing wrong?
its because of the attribute type="button" which is not firing the actionlistener.
when you declare this attribute (type="button") its not a p:commandButton anymore.
type="button" is push button purposes, it does not do any action or submit the form
try to remove type="button" attribute. it'd fire the actionlistener.
<p:commandButton id="cbViewExcluir"
image="ui-icon-circle-close"
onclick="dlgExcluir.show()"
title="Excluir"
update=":frmExcluir">
<!-- This is not working properly -->
<f:setPropertyActionListener value="#{atual}" target="# {publicoBean.publicoSelecionado}" />
</p:commandButton>
lemme know if this helps :)