I am using JSF 2.0 , I have a bean opcD (#SessionScoped). since I have defined the bean in SessionScoped after submitting the form and returning to the page the data remains inside the fields that is logic! But I would like to reinitialize my bean if I return again inside it.
But I do not want to destroy the session!
#ManagedBean(name="opcD")
#SessionScoped
public class NewOPCDetailBean implements Serializable {
Please find in below a part of my cod. I go from page (newopcheadpage.xhtml) relevant to opc managedBean to page (newopcdetailpage.xhtml)relevant to managedBean opcD. After submiting page(newopcdetailpage.xhtml) if I want to return to page (newopcheadpage.xhtml), I would like to see the fields blank(beans become reinitialized ).
#ManagedBean(name="opc",eager = true) #SessionScoped
public class NewOPCHeadBean implements Serializable {
private long partID;
private String partDesc;
private String taskDesc;
private Date date;
private String opcDesc;
private List<Part> partList;
public long getPartID() {
return partID;
}
public void setPartID(long partID) {
this.partID = partID;
}
public String getPartDesc() {
return partDesc;
}
public void setPartDesc(String partDesc) {
this.partDesc = partDesc;
}
public String getTaskDesc() {
return taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public Date getDate() {
return new Date();
}
public void setDate(Date date) {
this.date = new Date();
}
public String getOpcDesc() {
return opcDesc;
}
public void setOpcDesc(String opcDesc) {
this.opcDesc = opcDesc;
}
public List<Part> getPartList() {
return partList;
}
public void setPartList(List<Part> partList) {
this.partList = partList;
}
public List<Part> getPartsList(ActionEvent e)
{
HibernateDA hDA = new HibernateDA();
partList = hDA.partsList();
return partList;
}
public void showPartDesc()
{
HibernateDA hDA = new HibernateDA();
partDesc = hDA.showPartDescription(partID);
setPartDesc(partDesc);
}
public String submit()
{
return "/pages/admin/newopcdetailpage";
}
public void resetBean()
{
opcDesc="";
partID=0;
partDesc="";
}
}
#ManagedBean(name="opcD") #ViewScoped
public class NewOPCDetailBean implements Serializable {
private long partID;
private String taskDesc;
private long partNumber;
private Part part;
private Date date;
private String opcDesc;
private long task_opc_number;
private long task_nominal_time;
private OPCDetail opcDetail;
private List<Part> partList;
private static final ArrayList<OPCDetail> opcDetailList = new ArrayList<OPCDetail>();
//private static ArrayList<OPCDetail> opcDetailList = new ArrayList<OPCDetail>();
public ArrayList<OPCDetail> getOpcDetailList() {
return opcDetailList;
}
public long getPartID() {
return partID;
}
public void setPartID(long partID) {
this.partID = partID;
}
public long getPartNumber() {
return partNumber;
}
public void setPartNumber(long partNumber) {
this.partNumber = partNumber;
}
public Part getPart() {
return part;
}
public void setPart(Part part) {
this.part = part;
}
public String getTaskDesc() {
return taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public long getTask_nominal_time() {
return task_nominal_time;
}
public long getTask_opc_number() {
return task_opc_number;
}
public void setTask_opc_number(long task_opc_number) {
this.task_opc_number = task_opc_number;
}
public void setTask_nominal_time(long task_nominal_time) {
this.task_nominal_time = task_nominal_time;
}
public OPCDetail getOpcDetail() {
return opcDetail;
}
public void setOpcDetail(OPCDetail opcDetail) {
this.opcDetail = opcDetail;
}
public List<Part> getPartList() {
return partList;
}
public void setPartList(List<Part> partList) {
this.partList = partList;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getOpcDesc() {
return opcDesc;
}
public void setOpcDesc(String opcDesc) {
this.opcDesc = opcDesc;
}
public List<Part> getPartsList(ActionEvent e)
{
HibernateDA hDA = new HibernateDA();
partList = hDA.partsList();
return partList;
}
public void takePartNumber(ActionEvent e) throws Exception
{
Map m = e.getComponent().getAttributes();
partID = (Long)m.get("pID");
HibernateDA hDA = new HibernateDA();
part = hDA.takePart(partID);
partNumber = part.getPart_number();
opcDesc = (String) m.get("opcDesc");
date = (Date) m.get("opcDate");
}
public void addAction()
{
OPCDetail opcDetail1 = new OPCDetail(this.task_nominal_time,this.taskDesc);
int i = 0;
int j=0;
if (opcDetailList != null){
while (i < opcDetailList.size())
{
String tDesk = this.taskDesc.toLowerCase();
if (opcDetailList.get(i).getTask_desc().equals(tDesk))
{
j = 1;
break;
}
i++;
}
if(j == 0)
{
opcDetailList.add(opcDetail1);
}
}
taskDesc = "";
task_nominal_time = 0;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Edited",((OPCDetail) event.getObject()).getTask_desc());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
opcDetailList.remove((OPCDetail) event.getObject());
}
public void resetBean()
{
taskDesc = "";
task_nominal_time=0;
}
public String submitNewOPC()
{
int i = 0;
List<OPCDetail> opcDetailList1 = new ArrayList<OPCDetail>();
if (opcDetailList != null && opcDetailList.size() != 0){
while (i < opcDetailList.size())
{
OPCDetail opcDetail1 = new OPCDetail(i+1,opcDetailList.get(i).getTask_nominal_time(),opcDetailList.get(i).getTask_desc());
opcDetailList1.add(opcDetail1);
i++;
}
HibernateDA hDA = new HibernateDA();
OPC opc1 = new OPC();
opc1.setOpc_date(date);
opc1.setOpc_desc(opcDesc);
opc1.setPart(part);
opc1.setListOfTasks(opcDetailList1);
hDA.addNewOPC(opc1);
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#opcD}");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#opc}");
return "/index?faces-redirect=true";
}
}
<div style="border-bottom:2px solid #FFF">
<ui:insert name="header" >
<ui:include src="/header.xhtml" />
</ui:insert>
</div>
<div style="margin:0px 380px 0px 0px">
<h:form>
<p:panel header="Add New OPC" style="font-size: .6em">
<p:messages autoUpdate="true"/>
<h:panelGrid id="grid" columns="2" cellpadding="5">
<h:outputLabel for="opcDate" value="Date (dd-MM-yyyy):" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDate" value="#{opc.date}" required="true" label="Date(dd-MM-yyyy):" disabled="true">
<f:convertDateTime type="date" pattern="dd-MM-yyyy"/>
</p:inputText>
<p:message for="opcDate" />
<h:outputText value="" />
<h:outputLabel for="opcDesc" value="OPC Description:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDesc" value="#{opc.opcDesc}" required="true" label="OPC Description"/>
<p:message for="opcDesc" />
<h:outputText value="" />
<h:outputText value="Part Number " style="font-weight:bold; font-size: .8em" />
<p:selectOneMenu value="#{opc.partID}" required="true">
<p:ajax listener="#{opc.showPartDesc()}" update="partdesc" />
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{opc.partList}" var="parts" itemLabel="#{parts.part_number}" itemValue="#{parts.id}"/>
</p:selectOneMenu>
<h:outputLabel for="partdesc" value="Part Description:" style="font-weight:bold; font-size: .8em"/>
<h:outputText id="partdesc" value="#{opc.partDesc}" label="Part Description:"/>
<p:message for="partdesc" />
<h:outputText value="" />
</h:panelGrid>
</p:panel>
<p:commandButton value="Register" action="#{opc.submit()}" actionListener="#{opcD.takePartNumber}" ajax="false" icon="ui-icon-check" validateClient="true" style="margin-right:10px">
<f:attribute name="pID" value="#{opc.partID}"/>
<f:attribute name="opcDate" value="#{opc.date}"/>
<f:attribute name="opcDesc" value="#{opc.opcDesc}"/>
</p:commandButton>
</h:form>
</div>
<div style="padding-left: 500px">
<h:form style="font-size: .8em">
<p:commandButton value="Functions" action="/index?faces-redirect=true" ajax="false" icon="ui-icon-wrench"/>
</h:form>
</div>
</div>
<div style="border-bottom:2px solid #FFF">
<ui:insert name="header" >
<ui:include src="/header.xhtml" />
</ui:insert>
</div>
<div style="margin:0px 380px 0px 0px">
<h:form>
<p:panel header="Add New OPC" style="font-size: .6em">
<p:messages autoUpdate="true"/>
<h:panelGrid id="grid" columns="4" cellpadding="5">
<p:row>
<p:column colspan="10">
<h:outputLabel for="opcDate" value="Date (dd-MM-yyyy):" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDate" value="#{opc.date}" required="true" label="Date(dd-MM-yyyy):" disabled="true">
<f:convertDateTime type="date" pattern="dd-MM-yyyy"/>
</p:inputText>
<p:message for="opcDate" />
<h:outputText value="" />
<h:outputLabel for="opcDesc" value="OPC Description :" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDesc" value="#{opc.opcDesc}" required="true" label="OPC Description" disabled="true"/>
<p:message for="opcDesc" />
<h:outputText value="" />
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputLabel for="partnum" value="Part Number:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="partnum" value="#{opcD.partNumber}" required="true" label="Part Number" disabled="true"/>
</p:column>
<p:column>
<h:outputLabel for="partdesc" value="Part Description:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="partdesc" value="#{opc.partDesc}" required="true" label="Part Description" disabled="true"/>
</p:column>
</p:row>
</h:panelGrid>
</p:panel>
</h:form>
</div>
<div style="padding-left: 500px">
<h:form style="font-size: .8em">
<p:commandButton value="Functions" action="/index?faces-redirect=true" ajax="false" icon="ui-icon-wrench"/>
<p:commandButton value="Submit" action="#{opcD.submitNewOPC}" ajax="false" icon="ui-icon-wrench">
<f:actionListener binding="#{opc.resetBean()}"/>
</p:commandButton>
</h:form>
</div>
</div>
<div>
<h:form id="form1">
<p:growl id="messages" showDetail="true"/>
<p:panel header="OPC Detail" style="width: 400px;font-size: .6em">
<p:panelGrid columns="2">
<h:outputLabel for="taskDesk" value="Task Description: " />
<p:inputText id="taskDesk" value="#{opcD.taskDesc}"/>
<h:outputLabel for="tasknumTime" value="Task Numinal Time: " />
<p:inputText id="tasknumTime" value="#{opcD.task_nominal_time}"/>
<f:facet name="footer">
<h:commandButton value="Register Item" action="#{opcD.addAction()}"/>
</f:facet>
</p:panelGrid>
<p:spacer height="30px;"/>
<p:dataTable value="#{opcD.opcDetailList}" var="o" widgetVar="50" style="font-size: .3em" editable="true">
<f:facet name="header">
OPC Detail List
</f:facet>
<p:ajax event="rowEdit" listener="#{opcD.onEdit}" update=":form1:messages" />
<p:ajax event="rowEditCancel" listener="#{opcD.onCancel}" update=":form1:messages" />
<p:column>
<f:facet name="header">
<h:outputText value="Task Desc" />
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.task_desc}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.task_desc}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Numinal Time" />
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.task_nominal_time}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.task_nominal_time}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="" style="width:50px">
<p:rowEditor />
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</div>
I don't fully understand what are you trying to achieve ....
But I would like to reinitialize my bean if I return again inside it.
You mean, when you navigate away from page that is driven by the bean, and than when you navigate back to it, to reinitialize the bean again?
That is what #javax.faces.ViewScoped bean is for. It keeps the data of the fields in memory as long as you are on the view. When you navigate away from it, the data is no longer available. So turn you bean into #ViewScoped.
It seems you're structuring your beans in the wrong way. For your case, you should create another backing bean for the form using #RequestScoped. Then you can inject your #SessionScoped into the #RequestScoped bean to store whatever you need into the session.
Related
I have a p: datatable using rowedit and works fine, but when you delete an item datatable not updated.
#Named(value = "localesMB")
#SessionScoped
public class LocalesMB implements Serializable {
/**
* Creates a new instance of Activos
*/
public LocalesMB() {
}
private List<entidades.Locales> localesAll = new ArrayList<>();
private entidades.Locales selected = new Locales();
public Locales getSelected() {
return selected;
}
public void setSelected(Locales selected) {
this.selected = selected;
}
public List<Locales> getLocalesAll() {
return localesAll;
}
public void setLocalesAll(List<Locales> localesAll) {
this.localesAll = localesAll;
}
public void deleteSelect(Locales locales) {
this.selected = locales;
}
public void obtenerLocalesAll() {
try {
FacesContext ctx1 = FacesContext.getCurrentInstance();
ValueExpression vex1 = ctx1.getApplication().getExpressionFactory().createValueExpression(ctx1.getELContext(), "#{controladorMB}", ControladorMB.class);
ControladorMB cn = (ControladorMB) vex1.getValue(ctx1.getELContext());
this.localesAll = cn.getInterfaces().obtenerLocalesAll();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Error: obtenerActivosAll() " + e.getMessage());
}
}
public void eliminarLocal() {
try {
FacesContext ctx1 = FacesContext.getCurrentInstance();
ValueExpression vex1 = ctx1.getApplication().getExpressionFactory().createValueExpression(ctx1.getELContext(), "#{controladorMB}", ControladorMB.class);
ControladorMB cn = (ControladorMB) vex1.getValue(ctx1.getELContext());
cn.getInterfaces().eliminarLocal(this.selected);
this.localesAll = cn.getInterfaces().obtenerLocalesAll();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Error: eliminarLocal() " + e.getMessage());
}
}
public void onRowEdit(RowEditEvent event) {
try {
Locales ps = (Locales) event.getObject();
FacesContext ctx1 = FacesContext.getCurrentInstance();
ValueExpression vex1 = ctx1.getApplication().getExpressionFactory().createValueExpression(ctx1.getELContext(), "#{controladorMB}", ControladorMB.class);
ControladorMB cn = (ControladorMB) vex1.getValue(ctx1.getELContext());
cn.getInterfaces().modificarLocal(ps);
this.localesAll = cn.getInterfaces().obtenerLocalesAll();
JsfUtil.addSuccessMessage("Se ha cambiado el valor correctamente.");
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Error: onRowEdit() " + e.getMessage());
}
}
}
xhtml
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./../resources/css/default.css" rel="stylesheet" type="text/css" />
<link href="./../resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
<title>Activos</title>
<script language="javascript">
window.onload = function() {
PF('tb1').clearFilters();
};
</script>
</h:head>
<h:body>
<h:form id="frm1">
<p:growl id="growl" sticky="true" showDetail="true"/>
<p:panel header="Locales e Instalaciones" id="pn1">
<p:dataTable emptyMessage="No se encontraron elementos" editable="true" rowKey="#{item.idLocales}"
id="tabla_listado" var="item" paginator="true" widgetVar="tb1"
rows="25" value="#{localesMB.localesAll}">
<f:facet name="header">
<h:outputText value="Locales e Instalaciones: #{localesMB.localesAll.size()}"/>
</f:facet>
<p:ajax event="rowEdit" listener="#{localesMB.onRowEdit}"/>
<p:column headerText="Descripción">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{item.descripcion}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.descripcion}" style="width:95%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Ubicación">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{item.ubicacion}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.ubicacion}" style="width:95%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:20px">
<p:rowEditor/>
</p:column>
<p:column style="width:20px">
<p:commandButton id="selectButton256" oncomplete="PF('confirmation').show()" process="#this, tabla_listado" actionListener="#{localesMB.deleteSelect(item)}"
icon="ui-icon-trash" title="Eliminar" update=":frm1:confirmDialog">
</p:commandButton>
</p:column>
</p:dataTable>
</p:panel>
<p:confirmDialog appendTo="#(body)" id="confirmDialog" message="Confirma que desea eliminar a: #{localesMB.selected.descripcion}"
header="Mensaje de Confirmación" severity="alert" widgetVar="confirmation" closeOnEscape="true">
<p:commandButton id="confirm" value="Sí" update=":frm1" oncomplete="PF('confirmation').hide()"
actionListener="#{localesMB.eliminarLocal}" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"/>
<p:commandButton id="decline" value="No" onclick="PF('confirmation').hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
</p:confirmDialog>
</h:form>
that the problem, this code active the filter, but datatable dont have filterValue:
<script language="javascript">
window.onload = function() {
PF('tb1').clearFilters();
};
</script>
DataTable frm1:tabla_listado has filtering enabled but no filteredValue model reference is defined, for backward compatibility falling back to page viewstate method to keep filteredValue. It is highly suggested to use filtering with a filteredValue model reference as viewstate method is deprecated and will be removed in future.
Solution: remove script.
I use filterFunction method of datatable on primefaces 5.0. I want to filter birthday by date range on column header.
On browser console I receive this error:
<?xml version="1.0"
encoding="utf-8"?><partial-response><error><error-name>java.lang.ClassCastException</error-name><error-message><![CDATA[javax.faces.component.UIPanel
cannot be cast to
javax.faces.component.ValueHolder]]></error-message></error></partial-response>
Datatable :
<p:dataTable var="person" value="#{testDateRange.persons}"
id="personTable" paginator="true" styleClass="customTableStyle" editable="true"
rows="10" resizableColumns="true"
emptyMessage="No persons"
filteredValue="#{testDateRange.filteredPersons}"
widgetVar="dateRangeWidget" >
<p:column id="nameId" filterBy="name" sortBy="name" filterMatchMode="contains" headerText="Name">
<h:outputText value="#{person.name}" />
</p:column>
<p:column id="birthdayId" headerText="birthday" filterBy="birthday" filterFunction="#{testDateRange.filterByDate}">
<f:facet name="filter">
<p:calendar id="from" value="#{testDateRange.dateFrom}" styleClass="customCalendar" pattern="dd/MM/yyyy">
<p:ajax event="dateSelect" oncomplete="PF('dateRangeWidget').filter()" update="personTable"/>
</p:calendar>
<p:calendar id="to" value="#{testDateRange.dateTo}" styleClass="customCalendar" pattern="dd/MM/yyyy">
<p:ajax event="dateSelect" oncomplete="PF('dateRangeWidget').filter()" update="personTable"/>
</p:calendar>
</f:facet>
<h:outputText value="#{person.birthday}" >
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:outputText>
</p:column>
</p:dataTable>
Bean:
#Component("testDateRange")
#Scope("session")
public class TestDateRangeBean {
private List<Person> persons;
List<Person> filteredPersons;
private Date dateFrom;
private Date dateTo;
public TestDateRangeBean() {
persons = new ArrayList<>(Arrays.asList(
new Person("John", new Date(1357016400000L)),
new Person("Will",new Date(1357102800000L)),
new Person("Peter",new Date(1414900800000L)),
new Person("Cris", new Date(1438747200000L)),
new Person("Cemil", new Date(1436068800000L))
));
}
public boolean filterByDate(Object value, Object filter, Locale locale) {
// it fails before calling this method
String filterText = (filter == null) ? null : filter.toString().trim();
if(StringUtils.isEmpty(filterText)) {
return true;
}
if(value == null) {
return false;
}
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date filterDate;
try {
filterDate = df.parse(filterText);
} catch (ParseException e) {
return false;
}
return filterDate.after(dateFrom) && filterDate.before(dateTo);
}
//all the getters and setters
And I have a simple POJO Person class that contains only 'name' and 'birthday'.
How can I filter birthday by the dates I enter on column header. I see that it gets the UIPanel component instead of dates values. (I assume it expects one component with a value, and when it finds two components, it returns the container component itself, am I right?)
Thanks
Advanced solution:
JSF:
<p:column headerText="#{msg.date}" sortBy="#{bean.date}" filterBy="#{bean.date}" filterFunction="#{dateRangeFilter.filterByDate}">
<f:facet name="filter">
<h:inputHidden id="filter" />
</f:facet>
<f:facet name="header">
<h:outputText value="#{msg.date}" />
<br />
<p:calendar id="from" pattern="dd.MM.yyyy">
<p:ajax event="dateSelect" onstart="$(PrimeFaces.escapeClientId('#{p:component('filter')}'))[0].value = $(PrimeFaces.escapeClientId('#{p:component('from')}_input'))[0].value + '-' + $(PrimeFaces.escapeClientId('#{p:component('to')}_input'))[0].value" oncomplete="PF('dataTable').filter()" />
</p:calendar>
<p:calendar id="to" pattern="dd.MM.yyyy">
<p:ajax event="dateSelect" onstart="$(PrimeFaces.escapeClientId('#{p:component('filter')}'))[0].value = $(PrimeFaces.escapeClientId('#{p:component('from')}_input'))[0].value + '-' + $(PrimeFaces.escapeClientId('#{p:component('to')}_input'))[0].value" oncomplete="PF('dataTable').filter()" />
</p:calendar>
</f:facet>
<h:outputText value="#{bean.date}">
<f:convertDateTime type="date" dateStyle="medium" />
</h:outputText>
</p:column>
Filter Bean:
#Named
#ApplicationScoped
public class DateRangeFilter implements Serializable {
private static final Logger LOG = Logger.getLogger(DateRangeFilter.class.getName());
public boolean filterByDate(Object value, Object filter, Locale locale) {
String filterText = (filter == null) ? null : filter.toString().trim();
if (filterText == null || filterText.isEmpty()) {
return true;
}
if (value == null) {
return false;
}
DateFormat df = SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM);
Date filterDate = (Date) value;
Date dateFrom;
Date dateTo;
try {
String fromPart = filterText.substring(0, filterText.indexOf("-"));
String toPart = filterText.substring(filterText.indexOf("-") + 1);
dateFrom = fromPart.isEmpty() ? null : df.parse(fromPart);
dateTo = toPart.isEmpty() ? null : df.parse(toPart);
} catch (ParseException pe) {
LOG.log(Level.SEVERE, "unable to parse date: " + filterText, pe);
return false;
}
return (dateFrom == null || filterDate.after(dateFrom)) && (dateTo == null || filterDate.before(dateTo));
}
}
If you do not want the trickery with the hidden input field plus the benefit of reusing such a filter consider writing a composite component whose component type extends javax.faces.component.UIInput. Primefaces expects the filter to be a subtype of javax.faces.component.ValueHolder.
This is how the composite component might look like.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<!-- INTERFACE -->
<cc:interface componentType="dateRange">
<cc:attribute name="fromLabel"/>
<cc:attribute name="toLabel"/>
<cc:attribute name="value" type="so.example.DateRange"/>
<cc:attribute name="onvaluechanged"/>
</cc:interface>
<!-- IMPLEMENTATION -->
<cc:implementation>
<table>
<tr>
<td style="width: 15%; border: none;">
<h:outputText value="#{cc.attrs.fromLabel}"/>
</td>
<td style="width: 35%; border: none;">
<p:calendar id="startDateCalendar" value="#{cc.attrs.value.from}" maxdate="#{cc.attrs.value.to}">
<p:ajax event="dateSelect" update="endDateCalendar" oncomplete="#{cc.attrs.onvaluechanged}"/>
</p:calendar>
</td>
<td style="width: 15%; border: none;">
<h:outputText value="#{cc.attrs.toLabel}"/>
</td>
<td style="width: 35%; border: none;">
<p:calendar id="endDateCalendar" value="#{cc.attrs.value.to}" mindate="#{cc.attrs.value.from}" maxdate="#{cc.attrs.value.now}">
<p:ajax event="dateSelect" update="startDateCalendar" oncomplete="#{cc.attrs.onvaluechanged}"/>
</p:calendar>
</td>
</tr>
</table>
</cc:implementation>
Notice componentType="dateRange" in the cc:interface tag. This references the root component class of this composite component. Which is as simple as.
#FacesComponent("dateRange")
public class DateRangeComponent extends UIInput implements NamingContainer {
#Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
}
The value that the composite component takes is a simple POJO.
public class DateRange implements Serializable {
private Date from;
private Date to;
private boolean ignoreTime = true;
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
if (this.isIgnoreTime()) {
Calendar now = Calendar.getInstance();
now.setTime(from);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
this.from = now.getTime();
} else {
this.from = from;
}
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
if (this.isIgnoreTime()) {
Calendar now = Calendar.getInstance();
now.setTime(to);
now.set(Calendar.HOUR_OF_DAY, 23);
now.set(Calendar.MINUTE, 59);
now.set(Calendar.SECOND, 59);
this.to = now.getTime();
} else {
this.to = to;
}
}
public Date getNow() {
return new Date();
}
public boolean isIgnoreTime() {
return ignoreTime;
}
public void setIgnoreTime(boolean ignoreTime) {
this.ignoreTime = ignoreTime;
}
}
After all that the usage is very simple.
<p:column headerText="#{labels.date}"
sortBy="#{logIn.loginDate}"
filterBy="#{logIn.loginDate}"
filterFunction="#{logInTableBean.filterByDate}"
styleClass="datetime-column">
<f:facet name="filter">
<clx:dateRange fromLabel="#{labels.from}"
toLabel="#{labels.to}"
onvaluechanged="PF('logInTable').filter();"
value="#{logInTableBean.range}"/>
</f:facet>
<h:outputText value="#{logIn.loginDate}">
<f:convertDateTime type="both" dateStyle="long"/>
</h:outputText>
</p:column>
Also notice the custom filter function. Whis is as simple as
public boolean filterByDate(Object value, Object filter, Locale locale) {
Date colDate = (Date) value;
return this.range.getFrom().before(colDate) && this.range.getTo().after(colDate);
}
The whole thing will look like this.
Encountered same problem but in my case it was button in filter facet to show overlay panel with range slider inside.
To solve it use header facet instead:
<f:facet name="filter">
<!-- to hide default filter input -->
<h:inputHidden />
</f:facet>
<f:facet name="header">
<p:outputLabel value="birthday" /><br />
<p:calendar id="from" value="#{testDateRange.dateFrom}" styleClass="customCalendar" pattern="dd/MM/yyyy">
<p:ajax event="dateSelect" oncomplete="PF('dateRangeWidget').filter()" />
</p:calendar>
<p:calendar id="to" value="#{testDateRange.dateTo}" styleClass="customCalendar" pattern="dd/MM/yyyy">
<p:ajax event="dateSelect" oncomplete="PF('dateRangeWidget').filter()" />
</p:calendar>
</f:facet>
Also there is no need in update attribute in p:ajax components.
This is just Java 8 implementation of #Stephan's answer, using java.time class instead of Date.
The JSF section is almost identical except the date pattern.
<p:column headerText="Date" filterBy="#{passbook.createdAt}" filterFunction="#{applicationController.filterByDate}">
<f:facet name="filter">
<h:inputHidden id="filter" />
</f:facet>
<f:facet name="header">
<h:outputText value="Date" />
<br />
<p:calendar id="from" pattern="dd-MMM-yyyy" size="12">
<p:ajax event="dateSelect" onstart="$(PrimeFaces.escapeClientId('#{p:component('filter')}'))[0].value = $(PrimeFaces.escapeClientId('#{p:component('from')}_input'))[0].value + '>' + $(PrimeFaces.escapeClientId('#{p:component('to')}_input'))[0].value" oncomplete="PF('passbookTable').filter()" />
</p:calendar>
<h:outputText class="fa fa-arrows-h fa-2x" style="vertical-align: top;"/>
<p:calendar id="to" pattern="dd-MMM-yyyy" size="12">
<p:ajax event="dateSelect" onstart="$(PrimeFaces.escapeClientId('#{p:component('filter')}'))[0].value = $(PrimeFaces.escapeClientId('#{p:component('from')}_input'))[0].value + '>' + $(PrimeFaces.escapeClientId('#{p:component('to')}_input'))[0].value" oncomplete="PF('passbookTable').filter()" />
</p:calendar>
</f:facet>
<h:outputText value="#{passbook.createdAt}">
<f:convertDateTime type="date" dateStyle="medium" pattern="dd-MMM-yyyy"/>
</h:outputText>
Bean:
#Named
#ApplicationScoped
public class ApplicationController implements Serializable {
private static final Logger logger = LogManager.getLogger(ApplicationController.class.getName());
public boolean filterByDate(Object value, Object filter, Locale locale) {
String filterText = (filter == null) ? null : filter.toString().trim();
if (filterText == null || filterText.isEmpty()) {
return true;
}
if (value == null) {
return false;
}
DateTimeFormatter sdf = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
Instant instant = ((Date) value).toInstant(); //Zone : UTC+0
LocalDate dateValue = instant.atZone(ZoneId.of("Asia/Kolkata")).toLocalDate();
LocalDate dateFrom;
LocalDate dateTo;
try {
String fromPart = filterText.substring(0, filterText.indexOf(">"));
String toPart = filterText.substring(filterText.indexOf(">") + 1);
dateFrom = fromPart.isEmpty() ? null : LocalDate.parse(fromPart, sdf);
dateTo = toPart.isEmpty() ? null : LocalDate.parse(toPart, sdf);
} catch (Exception e) {
logger.error("unable to parse date: " + filterText, e);
return false;
}
return (dateFrom == null || dateValue.isAfter(dateFrom) || dateValue.isEqual(dateFrom))
&& (dateTo == null || dateValue.isBefore(dateTo) || dateValue.isEqual(dateTo));
}
I'm using primefaces 3.5 and watching a strange datatable behavior when editing data.
If I enter wrong data in 'year' field and click on the tick I get a message about mistake.
But if I don't click on the tick and click on the 'Add row' button I don't get a message. Only new row is added.
I expect to stay in edit mode. How to solve this problem?
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="In cell editing" />
<p:dataTable id="inCellEditing" var="car" value="#{dataTableController.cars}" rowKey="#{car.name}" editable="true">
<p:ajax event="rowEdit" listener="#{dataTableController.onEdit}" update=":mainForm:growl" />
<p:ajax event="rowEditCancel" listener="#{dataTableController.onCancel}" update=":mainForm:growl" />
<p:column headerText="Year">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{car.year}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{car.year}">
<p:ajax event="blur" update="#this"/>
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Name">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{car.name}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{car.name}" >
<f:selectItems value="#{dataTableController.carNames}"
var="name"
itemLabel="#{name}"
itemValue="#{name}" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Actions">
<p:rowEditor />
</p:column>
</p:dataTable>
<p:commandButton action="#{dataTableController.addRow()}" value="Add row" ajax="false"/>
</h:panelGrid>
public class DataTableController implements Serializable {
private List<Car> cars;
private Car selectedCar;
private Car[] selectedCars;
private List<Car> selectedCarsList;
private SelectItem[] carNamesOptions;
public DataTableController() {
cars = new ArrayList<Car>(CarConverter.cars.values());
}
public String[] getCarNames() {
return CarConverter.cars.keySet().toArray(new String[0]);
}
public SelectItem[] getCarNamesAsOptions() {
carNamesOptions = createFilterOptions(CarConverter.cars.keySet().toArray(new String[0]));
return carNamesOptions;
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
public void onEdit(RowEditEvent event) {
MessageUtil.addInfoMessage("car.edit", ((Car) event.getObject()).getName());
}
public void onCancel(RowEditEvent event) {
MessageUtil.addInfoMessage("car.edit.cancelled", ((Car) event.getObject()).getName());
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car[] selectedCars) {
this.selectedCars = selectedCars;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public List<Car> getSelectedCarsList() {
return selectedCarsList;
}
public void setSelectedCarsList(List<Car> selectedCarsList) {
this.selectedCarsList = selectedCarsList;
}
public void addRow(){
cars.add(new Car("",0));
}
}
I am testing the primefaces collector example given in Showcase for my code
I read somewhere that its necessary to override the equals and hashcode method for that.
Even after overriding the methods , I am still getting the same error.
Kindly tell me whats wrong in my code
User.java
#ManagedBean
public class User implements Serializable{
public String name;
public String designation;
public String division;
public User(String name,String division){
setName(name);
setDivision(division);
}
public User(){
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDivision() {
return division;
}
public void setDivision(String userDivision) {
this.division = userDivision;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
commApprover.java
#ManagedBean
#ViewScoped
public class CommApprover implements Serializable{
private User approver = new User();
private List<User> approvers = new ArrayList<User>();
public String reinit() {
approver = new User();
return null;
}
public User getApprover() {
return approver;
}
public void setApprover(User approver) {
this.approver = approver;
}
public List<User> getApprovers() {
return approvers;
}
public void setApprovers(List<User> approvers) {
this.approvers = approvers;
}
#Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
if (approver!= null ? !approver.equals(this.approver) : this.approver != null)
return false;
return true;
}
#Override
public int hashCode()
{
int result = approver.hashCode();
return result;
}
}
index.xhtml
<p:growl id="msgs" />
<p:panel header="Approval Route ">
<h:panelGrid columns="3" id="grid">
<h:outputText value="Name*" />
<h:outputText value="Designation*" />
<h:outputText value="Division*" />
<p:inputText id="app_name" value="#{commApprover.approver.name}" required="true"/>
<p:inputText id="app_designation" value="#{commApprover.approver.designation}" required="true"/>
<p:inputText id="app_division" required="true" value="# {commApprover.approver.division}" />
<p:commandButton id="btn_add" value="Add" update="approvers #parent" action="#{commApprover.reinit}" >
<p:collector value="#{commApprover.approver}" addTo="#{commApprover.approvers}" />
</p:commandButton>
</h:panelGrid>
</p:panel>
<p:outputPanel id="approvers">
<p:dataTable id="approversTable" value="#{commApprover.approvers}" var="approver">
<p:column>
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{approver.name}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Designation" />
</f:facet>
<h:outputText value="#{approver.designation}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Division" />
</f:facet>
<h:outputText value="#{approver.division}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Operation" />
</f:facet>
<p:commandLink ajax="true" value="Remove" update=":appform:approvers" process=":appform:approvers">
<p:collector value="#{approver}" removeFrom="#{commApprover.approvers}" />
</p:commandLink>
</p:column>
</p:dataTable>
</p:outputPanel>
</h:form>
This post is old but I ran into the same problem and after some debuging I found out that this problem is related to incorrectly implemented hashCode and equals, when using converters or p:collector you have to implement hashCode and equals to compare all fields in your entity otherwise it fails even if the item you are trying to remove is the correct one. Also it is recomended that you override those properties in your Pojo not in you ManagedBean. This post helped me to understand the problem https://blog.art-of-coding.eu/jsf-converters-and-equals-hashcode/
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 :)