I have a piece of code similar to "Data Table - Instant Row Selection". However, when I break it down into composite components the selection values are not displayed. I have a suspicion it's caused by PrimeFaces code.
Below is the code that doesn't work:
viewApplicationConfig.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:dti="http://java.sun.com/jsf/composite/dti"
template="../../templates/baseTemplate.xhtml">
<f:metadata>
<f:viewParam name="contextApplicationId" value="#{viewApplicationConfig.contextApplicationId}"/>
</f:metadata>
<ui:define name="title">#{viewApplicationConfig.pageTitle}</ui:define>
<ui:define name="content">
<p:panel id="panel" header="#{viewApplicationConfig.pageTitle}" style="width: 1280px">
<ui:remove>
------ ApplicationFilterCriteriaPanel ----------
</ui:remove>
<dti:dtiPanel value="#{viewApplicationConfig.getPanelBean('ApplicationFilterCriteriaPanel')}"
toggleable="true" toggleSpeed="500">
<dti:dtiLayer id="#{viewApplicationConfig.getLayer('ApplicationFilterCriteriaLayer').getLayerId()}">
<div style="width: 600px;">
<div style="float: left">
<h:dataTable
value="#{viewApplicationConfig.getLayerFields('ApplicationFilterCriteriaLayer')}"
var="field">
<h:column>
<dti:dtiField field="#{field}" record="#{record}"/>
</h:column>
</h:dataTable>
</div>
</div>
</dti:dtiLayer>
</dti:dtiPanel>
<ui:remove>
------ End ApplicationFilterCriteriaPanel ----------
</ui:remove>
<ui:remove>
------ ApplicationGridPanel ----------
</ui:remove>
<dti:dtiPanel value="#{viewApplicationConfig.getPanelBean('ApplicationGridPanel')}"
toggleable="true" toggleSpeed="500">
<dti:dtiLayer id="#{viewApplicationConfig.getLayer('ApplicationGridLayer_GH').getLayerId()}">
<div style="width: 600px;">
<div style="float: left">
<h:dataTable value="#{viewApplicationConfig.getLayerFields('ApplicationGridLayer_GH')}"
var="field">
<h:column>
<dti:dtiField field="#{field}" record="#{record}"/>
</h:column>
</h:dataTable>
</div>
</div>
</dti:dtiLayer>
<ui:remove>
------ DTI GRID ----------
</ui:remove>
<dti:dtiGrid columns="#{viewApplicationConfig.getLayerFields('ApplicationGridLayer_GH')}"
dataBean="#{viewApplicationConfig}"/>
<ui:remove>
------ END DTI GRID ----------
</ui:remove>
<ui:remove>
------ END ApplicationGridPanel ----------
</ui:remove>
</dti:dtiPanel>
<ui:remove>
------ Debugging Code --------------
<h1 class="title ui-widget-header ui-corner-all"
style="width: 1200px; margin-left: 20px;"><h:outputLabel
value="Welcome #{loginBean.name}"></h:outputLabel></h1>
<h:outputText value="Theme: #{guestPreferences.theme}"/><br/>
<h:outputText
value="Selected contextApplicationId -- getContextApplicationId(): #{viewApplicationConfig.contextApplicationId}"/>
<br/>
<h:outputText value="Grid Header -- getXmlHeader(): #{viewApplicationConfig.xmlHeader}"/> <br/>
<h:outputText
value="Grid Header Fields -- getXmlHeaderFields(): #{viewApplicationConfig.xmlHeaderFields}"/>
<br/>
<h:outputText
value="Grid Header Layer Fields -- getXmlHeaderLayerFields(): #{viewApplicationConfig.xmlHeaderLayerFields}"/>
<br/>
<h:outputText value="Page Fields -- getPageFields(): #{viewApplicationConfig.pageFields}"/> <br/>
<h:outputText value="Layers getLayers(): #{viewApplicationConfig.layers}"/> <br/>
<h:outputText
value="Layers getLayer(ApplicationGridLayer_GH): #{viewApplicationConfig.getLayer('ApplicationGridLayer_GH')}"/>
<br/>
<h:outputText
value="Layers getLayerFields(ApplicationGridLayer_GH): #{viewApplicationConfig.getLayerFields('ApplicationGridLayer_GH')}"/>
<br/>
<div class="entry">
<h:form>
<h:commandLink actionListener="#{viewApplicationConfig.navigateToPageConfig}"
value="Click on contextApplicationId"/>
<p:dataTable var="record" value="#{viewApplicationConfig.applications}"
paginator="true" rows="5" id="entityTable"
style="width:1220px">
<f:facet name="header">
Applications -- Size: #{viewApplicationConfig.applications.size()}
</f:facet>
<p:column headerText="ClientId" style="width:100px">
<h:outputText value="#{record.fieldNameList}"/>
</p:column>
</p:dataTable>
</h:form>
</div>
------ End Debugging Code ----------
</ui:remove>
</p:panel>
</ui:define>
</ui:composition>
dtiPanel.xhtml
<!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:p="http://primefaces.prime.com.tr/ui"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name="value" required="true"/>
<composite:attribute name="toggleable" required="true"/>
<composite:attribute name="closable"/>
<composite:attribute name="toggleSpeed"/>
<composite:attribute name="collapsed"/>
</composite:interface>
<composite:implementation>
<p:panel id="#{cc.attrs.value.id}" header="#{cc.attrs.value.title}"
toggleable="#{cc.attrs.toggleable}" closable="#{cc.attrs.closable}"
toggleSpeed="#{cc.attrs.toggleSpeed}"
collapsed="#{cc.attrs.collapsed}">
<composite:insertChildren/>
</p:panel>
</composite:implementation>
</html>
dtiLayer.xhtml
<!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:p="http://primefaces.prime.com.tr/ui"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name="id" required="true"/>
<composite:attribute name="hidden"/>
</composite:interface>
<composite:implementation>
<p:outputPanel id="#{cc.attrs.id}" rendered="#{!cc.attrs.hidden}">
<composite:insertChildren/>
</p:outputPanel>
</composite:implementation>
</html>
dtiGrid.xhtml
<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:p="http://primefaces.prime.com.tr/ui"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:dti="http://java.sun.com/jsf/composite/dti">
<composite:interface>
<composite:attribute name="columns" required="true"/>
<composite:attribute name="dataBean" required="true"/>
</composite:interface>
<composite:implementation>
<div class="entry">
<h:form id="gridForm">
<p:ajaxStatus style="width:32px;height:32px;">
<f:facet name="start">
<h:graphicImage value="/core/images/design/ajaxloading.gif"/>
</f:facet>
<f:facet name="complete">
<h:outputText value=""/>
</f:facet>
</p:ajaxStatus>
<f:facet name="header">
<p:messages/>
</f:facet>
<p:growl id="growl" showDetail="true"/>
<h:panelGrid columns="2">
<p:panel header="Export All Data">
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/excel.png"/>
<p:dataExporter type="xls" target="entityTable"
fileName="entityDialog"/>
</h:commandLink>
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/pdf.png"/>
<p:dataExporter type="pdf" target="entityTable"
fileName="entityDialog"/>
</h:commandLink>
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/csv.png"/>
<p:dataExporter type="csv" target="entityTable"
fileName="entityDialog"/>
</h:commandLink>
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/xml.png"/>
<p:dataExporter type="xml" target="entityTable"
fileName="entityDialog"/>
</h:commandLink>
</p:panel>
<p:panel header="Export Page Data">
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/excel.png"/>
<p:dataExporter type="xls" target="entityTable"
fileName="entityDialog" pageOnly="true"/>
</h:commandLink>
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/pdf.png"/>
<p:dataExporter type="pdf" target="entityTable"
fileName="entityDialog" pageOnly="true"/>
</h:commandLink>
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/csv.png"/>
<p:dataExporter type="csv" target="entityTable"
fileName="entityDialog" pageOnly="true"/>
</h:commandLink>
<h:commandLink>
<p:graphicImage value="/core/images/primefaces/xml.png"/>
<p:dataExporter type="xml" target="entityTable"
fileName="entityDialog" pageOnly="true"/>
</h:commandLink>
</p:panel>
</h:panelGrid>
<p:dataTable var="record" value="#{cc.attrs.dataBean.applications}"
paginator="true" rows="5" id="entityTable"
selection="#{cc.attrs.dataBean.selectedRecord}" selectionMode="single"
rowSelectListener="#{cc.attrs.dataBean.onRowSelect}"
onRowSelectUpdate="rowForm:display growl"
rowUnselectListener="#{cc.attrs.dataBean.onRowUnselect}"
onRowUnselectUpdate="growl"
onRowSelectComplete="rowDialog.show()" update="rowForm:display"
dblClickSelect="true"
style="width:1220px">
<f:facet name="header">
Applications -- Size: #{cc.attrs.dataBean.applications.size()}
</f:facet>
<c:forEach var="column" items="#{cc.attrs.columns}">
<c:choose>
<c:when test="#{fn:toUpperCase(column.fieldId)=='SELECT_IND_GH'}">
<p:column selectionMode="multiple" style="width:20px"/>
</c:when>
<c:otherwise>
<p:column headerText="#{column.label}" filterBy="#{record.getFieldValue(fn:substringBefore(column.fieldId, '_GH'))}"
sortBy="#{record.getFieldValue(fn:substringBefore(column.fieldId, '_GH'))}" style="width:100px">
<c:choose>
<c:when test="#{not empty column.href}">
<h:link outcome="viewApplicationConfig"
value="#{record.getFieldValue(fn:substringBefore(column.fieldId, '_GH'))}">
<f:param name="pageUrl" value="#{column.href}"/>
</h:link>
</c:when>
<c:otherwise>
<h:outputText
value="#{record.getFieldValue(fn:substringBefore(column.fieldId, '_GH'))}"/>
<ui:remove>
<br/>Field Id: #{column.fieldId}
<br/>Data Type: #{column.datatype}
<br/>Display Type: #{column.displayType}
<br/>Read Only: #{column.isReadOnly}
<br/>Visible: #{column.isVisible}
<br/>HREF: #{column.href}
</ui:remove>
</c:otherwise>
</c:choose>
</p:column>
</c:otherwise>
</c:choose>
</c:forEach>
</p:dataTable>
</h:form>
<p:dialog header="Edit Row" widgetVar="rowDialog"
resizable="false" width="700">
<h:form id="rowForm">
<dti:dtiPanel id="display" value="#{viewApplicationConfig.getPanelBean('ApplicationGridDetailPanel')}"
toggleable="true" toggleSpeed="500" collapsed="false">
<dti:dtiLayer id="#{viewApplicationConfig.getLayer('ApplicationGridDetailLayer').getLayerId()}">
<div style="width: 600px;">
<div style="float: left">
<h:dataTable
value="#{viewApplicationConfig.getLayerFields('ApplicationGridDetailLayer')}"
var="field">
<h:column>
<ui:remove>
<h:outputText
value="testX: #{cc.attrs.dataBean.selectedRecord.getFieldValue('baseShortDescription')}"/> /
<h:outputText value="testX 1: #{cc.attrs.dataBean.selectedRecord.size}"/>
</ui:remove>
<dti:dtiField field="#{field}" record="#{cc.attrs.dataBean.selectedRecord}"/>
</h:column>
</h:dataTable>
</div>
</div>
</dti:dtiLayer>
</dti:dtiPanel>
</h:form>
</p:dialog>
</div>
</composite:implementation>
</html>
dtiField.xhtml
<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.prime.com.tr/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name="field" required="true"/>
<composite:attribute name="record" type="dti.oasis.recordset.Record" required="true"/>
</composite:interface>
<composite:implementation>
<ui:remove>
<h:outputText value="FieldName 0: #{cc.attrs.record.getFieldNameList().get(0)}"/> / <h:outputText
value="test 1: #{cc.attrs.record.size()}"/>
</ui:remove>
<p:outputPanel rendered="#{cc.attrs.field.isVisible and !fn:endsWith(cc.attrs.field.fieldId, '_GH')}">
<div id="#{cc.clientId}">
<h:panelGrid columns="2">
<div style="width: 100%">
<div style="float: left; #{cc.attrs.field.style}">
#{cc.attrs.field.label}
</div>
<div style="float: right">
<h:outputText value="#{cc.attrs.record.getFieldValue(cc.attrs.field.fieldId)}" rendered="#{cc.attrs.field.isReadOnly}"/>
<h:inputText rendered="#{cc.attrs.field.displayType == 'TEXT' and !cc.attrs.field.isReadOnly}"
value="#{cc.attrs.record.getFieldValue(cc.attrs.field.fieldId)}"/>
<h:selectOneMenu rendered="#{cc.attrs.field.displayType == 'SELECT' and !cc.attrs.field.isReadOnly}">
<f:selectItems/>
</h:selectOneMenu>
<h:selectBooleanCheckbox rendered="#{cc.attrs.field.displayType == 'CHECKBOX' and !cc.attrs.field.isReadOnly}"
value="#{cc.attrs.record.getFieldValue(cc.attrs.field.fieldId)}"/>
<ui:remove>
<br/>Display Type: #{cc.attrs.field.displayType}
<br/>Visible: #{cc.attrs.field.isVisible}
<br/>Read Only: #{cc.attrs.field.isReadOnly}
<br/>Field Id: #{cc.attrs.field.fieldId}
<br/>Rows: #{cc.attrs.field.rowNum}
<br/>Columns: #{cc.attrs.field.colNum}
<br/>Field Value: #{cc.attrs.record.getFieldValue(cc.attrs.field.fieldId)}
</ui:remove>
</div>
</div>
</h:panelGrid>
</div>
</p:outputPanel>
</composite:implementation>
</html>
The bean class looks like the following:
package com.dti.admin.cwb.appconfigmgr.view;
import com.dti.admin.view.BaseAdminManagedBean;
import com.dti.view.ManagedBeanUtils;
import dti.admin.cwb.appconfigmgr.AppConfigManager;
import dti.oasis.recordset.Record;
import dti.oasis.recordset.RecordSet;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;
#Component("viewApplicationConfig")
#Scope("request")
public class ViewApplicationConfig extends BaseAdminManagedBean implements Serializable {
private AppConfigManager appConfigManager;
private String contextApplicationId;
private List<Record> applications;
private RecordSet applicationRecordSet;
//////
private Record selectedRecord;
public Record getSelectedRecord() {
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- getSelectedRecord --");
if(selectedRecord!=null){
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- getSelectedRecord -- getRecordNumber: "+
selectedRecord.getRecordNumber());
}
return selectedRecord;
}
public void setSelectedRecord(Record selectedRecord) {
this.selectedRecord = selectedRecord;
}
//////
public void onRowSelect(SelectEvent event) {
System.out.println("onRowSelect");
FacesMessage msg = new FacesMessage("Entity Selected",
(String)((Record) event.getObject()).getFieldValue("baseShortDescription"));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
System.out.println("onRowUnselect");
FacesMessage msg = new FacesMessage("Entity Unselected",
(String)((Record) event.getObject()).getFieldValue("baseShortDescription"));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
///////////////////
public ViewApplicationConfig() {
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- " + "ViewApplicationConfig()");
}
#Autowired()
public ViewApplicationConfig(AppConfigManager appConfigManager) {
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- "
+ "ViewApplicationConfig(AppConfigManager appConfigManager)");
this.appConfigManager = appConfigManager;
this.setPageId("MaintainApplicationConfig");
this.setAnchorColumnName("applicationId");
}
#PostConstruct
public void onLoad() throws Exception {
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- " + "onLoad()");
HttpServletRequest request = ManagedBeanUtils.getHttpServletRequest();
init(request);
//Grid Header
setXmlHeader(getGridHeader(request));
//From Action Class
Record inputRecord = getInputRecord(request);
//From prime-movicollector -- sort of
if(applicationRecordSet == null) {
applicationRecordSet = appConfigManager.loadAllWebApplications(inputRecord);
applications = ManagedBeanUtils.convertRecordSetToList(applicationRecordSet);
}
//
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX " + applications.size());
}
#PreDestroy
public void onUnload() {
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- " + "onUnload()");
terminate();
}
public void navigateToPageConfig(ActionEvent actionEvent) {
System.out.println("navigateToPageConfig("+contextApplicationId+")");
String pageUrl = "/pageconfigmgr/maintainPageConfig.do?contextApplicationId=" + contextApplicationId;
navigateToPage(pageUrl);
}
public AppConfigManager getAppConfigManager() {
return appConfigManager;
}
public void setAppConfigManager(AppConfigManager appConfigManager) {
this.appConfigManager = appConfigManager;
}
public List<Record> getApplications() {
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- " + "getApplications()");
return applications;
}
public void setApplications(List <Record> applications) {
System.out.println(new java.sql.Timestamp(System.currentTimeMillis()) + " -- "
+ this.getClass().getName() + " -- " + "setApplications(RecordSet applications)");
this.applications = applications;
}
public RecordSet getApplicationRecordSet() {
return applicationRecordSet;
}
public void setApplicationRecordSet(RecordSet applicationRecordSet) {
this.applicationRecordSet = applicationRecordSet;
}
public String getContextApplicationId() {
return contextApplicationId;
}
public void setContextApplicationId(String contextApplicationId) {
this.contextApplicationId = contextApplicationId;
}
}
Did anyone have a similar issue using composite components, p:dataTable and p:dialog?
I didn't read through the whole code as you didn't point me to a specific piece of code like "when I click the <p:commandButton id="someButton" ..." so I'm just 'taking a guess'.
I see the backing bean is request scoped using Spring's container. I think the problem you're experiencing is that the bean has the lifespan of one request. If you're doing AJAX things like selecting rows in a data table you need a view scoped bean. Have a look at this question for an explanation of different scopes.
I'm also guessing that you now want to use a view scoped bean, and I know Spring doesn't have a #Scope("view") you can use. Luckily Cagatay Civici came to the rescue and has posted a solution on his blog.
Related
I have an issue with primefaces datagrid.I am following this example1, trying to update the dialog box with the selected values on click of p:commandLink. The Dialog doesnt work, doesnt show. I am using primefaces-4.0 on GlassFish Server 4.0. I've replaced the bean and its methods with my bean.
This is what i did.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<body>
<ui:composition template="./plantilla/plantillaPrincipal.xhtml">
<ui:define name="content">
<h:form id="form" class="well">
<h1>#{accionesController.tipo}</h1>
<p:dataGrid var="r" value="#{accionesController.lista}" columns="3"
rows="3" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="3,6,9">
<p:panel header="#{r.title}" style="text-align:center">
<h:panelGrid columns="1" style="width:100%">
<p:graphicImage value="/img/libros/#{r.ubicacion}.jpg"/>
<h:outputText value="#{r.author}" />
<p:commandLink update=":form:carDetail" oncomplete="PF('carDialog').show()" title="View Detail">
<h:outputText styleClass="ui-icon ui-icon-search" style="margin:0 auto;" />
<f:setPropertyActionListener value="#{r}"
target="#{r.libroseleccionado}" />
</p:commandLink>
</h:panelGrid>
</p:panel>
</p:dataGrid>
<p:dialog header="Car Detail" id="carDialog" widgetVar="carDialog" modal="true">
<p:outputPanel id="carDetail" style="text-align:center;">
<p:graphicImage value="/img/libros/#{r.libroseleccionado.ubicacion}.jpg"/>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="modelNo" value="Model No: " />
<h:outputText id="modelNo" value="#{r.libroseleccionado.author}" />
<h:outputLabel for="year" value="Year: " />
<h:outputText id="year" value="#{r.libroseleccionado.title}" />
</h:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
My bean
#Component()
#ManagedBean
#RequestScoped
#ComponentScan("pe.egcc.eureka.app.layer.service")
public class AccionesController {
#Autowired
private AccionesService accionesService;
private List<Map<String, Object>> lista;
private String tipo;
private Books libroseleccionado;
public void setLibroseleccionado(Books libroseleccionado) {
this.libroseleccionado = libroseleccionado;
}
public Books getLibroseleccionado() {
return libroseleccionado;
}
public String getTipo() {
return tipo;
}
public List<Map<String, Object>> getLista() {
if (lista == null) {
lista = new ArrayList<Map<String, Object>>();
}
return lista;
}
public String consultarLibros() {
String destino;
lista = accionesService.listarLibros();
tipo="Todos los Libros";
destino = "listarLibros";
return destino;
}
public String consultarLibrosLiteratura() {
String destino;
tipo="Libros de Literatura";
lista = accionesService.listarLibrosLiteratura();
destino = "listarLibros";
return destino;
}
public String consultarLibrosInformatica() {
String destino;
tipo="Libros de Informática";
lista = accionesService.listarLibrosInformatica();
destino = "listarLibros";
return destino;
}
public String consultarArticulos() {
String destino;
tipo="ArtÃculos Diversos";
lista = accionesService.listarArticulos();
destino = "listarLibros";
return destino;
}
}
If anyone can point me in the right direction that'd be great. Sorry for the huge post, it needed a bit of explaining to make it coherent. Hopefully it makes sense. Thanks.
I discovered some compatibility problems between primefaces and twitter bootstrap, so I replaced the primefaces modal with a boostrap modal but keeping the outputPanel in order to get updated the data and changed from r.libroelegito to accionesController.libroelegido. Here is the code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:k="http://xmlns.jcp.org/jsf/passthrough">
<h:body>
<ui:composition template="./plantilla/plantillaPrincipal.xhtml">
<ui:define name="content">
<h:form id="form">
<h1>#{accionesController.tipo}</h1>
<p:dataGrid var="r" value="#{accionesController.lista}" columns="3"
rows="3" paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="3,6,9">
<p:panel header="#{r.title}" style="text-align:center">
<h:panelGrid columns="1" style="width:100%">
<p:graphicImage value="/img/libros/#{r.ubicacion}.jpg"/>
<h:outputText value="#{r.book_id}" />
<h:outputText value="#{r.author}" />
<p:commandButton icon="ui-icon-search" update=":form:carDetail" title="View Detail" k:data-toggle="modal" k:data-target="#vermasinformacion">
<f:setPropertyActionListener value="#{r}" target="#{accionesController.libroelegido}" />
</p:commandButton>
</h:panelGrid>
</p:panel>
</p:dataGrid>
<!--</p:dialog>-->
<div class="modal fade" id="vermasinformacion" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="panel panel-default">
<div class="panel-body">
<p:outputPanel id="carDetail" style="text-align:center;">
<legend>#{accionesController.libroelegido.title}</legend>
<p:graphicImage value="/img/libros/#{accionesController.libroelegido.ubicacion}.jpg"/>
<h:panelGrid columns="2" cellpadding="5" style="text-align: left">
<h:outputLabel for="idbook" value="Registro ISBN: " />
<h:outputText id="idbook" value="#{accionesController.libroelegido.book_id}002014" />
<h:outputLabel for="autorlibro" value="Autor :" />
<h:outputText id="autorlibro" value="#{accionesController.libroelegido.author}" />
<h:outputLabel for="preciolibro" value="Precio :" />
<h:outputText id="preciolibro" value="$ #{accionesController.libroelegido.price}" />
<h:commandButton value="Comprar" class="btn btn-primary"/>
<h:commandButton value="Agregar al carrito" class="btn btn-default"/>
</h:panelGrid>
</p:outputPanel>
</div>
</div>
</div>
</div>
</div>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
I got some issue regarding Primefaces. There is a requirement that when we change language in my top panel from Engish to Arabic the entire layout should be displayed in right to left position (Like mirror image applying to all inner pages).please help me out.
i am including english version layout,top panel and controller beans.
1.layout
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
<style type="text/css">
.ui-growl{
left:20px;
}
</style>
</h:head>
<body>
<ui:composition template="/home/template/common/commonLayout.xhtml">
<ui:define name="content">
<h:form enctype="multipart/form-data" dir="#{localeControllerBean.direction}" id="form1">
<div id="add">
<p:growl id="msgs" autoUpdate="true" display="icon" style="left:20px"></p:growl>
</div>
<p:panel header="#{msg['sponsor_detail']}">
<h:panelGrid columns="2">
<f:event listener="#{localeControllerBean.islang}" type="preRenderView" />
<p:outputLabel for="sname" value="#{msg['sponsor_name']}"
styleClass="label" />
<p:inputText id="sname" value="#{sponsorBean.sponsor_name}"
required="true" requiredMessage="#{msg['sponsor_name_msg']}"
styleClass="input">
<f:validator validatorId="sponsorValidator" />
</p:inputText>
<p:outputLabel for="sadd" value="#{msg['sponsoraddress']}:"
styleClass="label" />
<p:inputText id="sadd" value="#{sponsorBean.s_address}"
required="true" requiredMessage="#{msg['Sponsor_address_msg']}"
styleClass="input" />
<p:outputLabel for="smb" value="#{msg['sponsor_mbno']}:"
styleClass="label" />
<p:inputText id="smb" value="#{sponsorBean.s_mobile_no}"
required="true" requiredMessage="#{msg['sponsor_mbno_msg']}"
styleClass="input" />
<p:outputLabel for="ss" value="#{msg['sponsor_status']}:" styleClass="label" />
<p:inputText id="ss" value="#{sponsorBean.status}" required="true"
requiredMessage="#{msg['sponsor_mbno_msg']}" styleClass="input" />
</h:panelGrid>
<p:commandButton id="submit" value="#{msg['save']}" ajax="false"
action="#{sponsorBean.save}" style="margin-bottom:50px;"
update="msgs" />
<p:commandButton type="reset" value="#{msg['reset']}"
style="margin-bottom:50px;margin-left:30px;" ajax="false" />
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
2.toppanel Here i change language..
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<body>
<ui:composition>
<h:form>
<p:growl id="messages" >
<p:toolbar style="Font-size:small;">
<p:toolbarGroup align="left">
<h:outputText value="User : " style=" margin-left:15px;" />
<h:outputText value="#{loginBean.username}">
</h:outputText>
<p:commandButton value="Logout" action="#{loginBean.doLogout}" icon="ui-icon-extlink" />
</p:toolbarGroup>
<p:toolbarGroup align="right">
<p:commandButton value="#{loginBean.toggleButton}" action="#{loginBean.goHome}" icon="ui-icon-home"/>
<p:inputText id="firstname" value="#{manageEmployee.search}" dir="ltr" styleClass="input" style="margin-right:15px" />
<h:selectOneMenu
value="#{manageEmployee.searchFilter}" style="FONT-STYLE: plain; FONT-SIZE:small;margin-right:10px">
<f:selectItem itemLabel="All" itemValue="All" />
<f:selectItem itemLabel="Search by company" itemValue="company" />
<f:selectItem itemLabel="Search by sponsor" itemValue="sponsor" />
</h:selectOneMenu>
<p:commandButton id="submit" value="Search" ajax="false"
action="#{manageEmployee.searchRecords}" update="msgs" style="margin-left:10px" icon="ui-icon-search" />
<h:selectOneMenu value="#{localeBean.language}" onchange="submit()" style="margin-left:10px" >
<f:selectItem itemValue="en" itemLabel="English" />
<f:selectItem itemValue="ar" itemLabel="Arabic" />
</h:selectOneMenu>
</p:toolbarGroup>
</p:toolbar></p:growl>
</h:form>
</ui:composition>
</body>
</html>
3.Local Bean contoller:
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
#ManagedBean
#SessionScoped
public class LocaleBean {
private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
public Locale getLocale() {
return locale;
}
public String getLanguage() {
return locale.getLanguage();
}
public void setLanguage(String language) {
locale = new Locale(language);
FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("user", locale);
// session.setAttribute("language", language);
}
public String save()
{
return "homePage";
}
}
4.Language controller:
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.http.HttpSession;
#ManagedBean
#SessionScoped
public class LocaleControllerBean {
public static String dir="";
private String direction="";
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public void islang(ComponentSystemEvent event)
{
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
Locale l=(Locale) session.getAttribute("user");
if(l.toString().equals("ar"))
{
// dir="rtl";
setDirection("rtl");
}
else
{
setDirection("ltr");
// dir="ltr";
}
System.out.println("locale"+l);
facesContext.getViewRoot().setLocale(l);
}
}
The RTL support is something new in primefaces. I think it is not possible, just to have the whole page looking like a mirror image without actually recreating the page. The css itself probably will not do it, so you will need to create a separate page (or set of pages) to which you will be redirected after changing your locale.
More about RTL support in primefaces can be found here: http://code.google.com/p/primefaces/issues/detail?id=3890 and as you can see- it is component, by component, rather than global.
PROBLEM:
The PrimeFaces "p:focus" tag is not focusing.
-I.e., when the xhtml page is presented to the user, no input fields are in focus.
QUESTION:
Why not? How can I get "p:focus" to work properly in this simple app?
(NOTE: using Java 6, Mojarra v2.1.11, PrimeFaces v3.4.2)
index.jsp
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<title>testcal2 - index.xhtml</title>
<meta charset="utf-8" />
</h:head>
<h:body>
<h:form id="queryForm">
<f:event type="postValidate" listener="#{testBean.validate}" />
<h:panelGroup id="msgsx">
<p:messages showSummary="true"/>
</h:panelGroup>
<p:panel id="queryPanel" header="Test p:focus..." style="width:100%;">
<p:focus context="queryPanel"/>
<h:panelGroup id="msgs" style="height:1.5em; text-align: center;display:block">
<p:message id="lastName_msg" for="lastName" style="display:none;" showSummary="false"/>
<p:message id="birthDate_msg" for="birthDate" style="display:none;" showSummary="false"/>
<p:message id="startDate_msg" for="startDate" style="display:none;" showSummary="false"/>
</h:panelGroup>
<h:panelGroup id="querypanelgroup" style="display:inline-block;">
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Last Name:" for="lastName"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="lastName"
value="#{testBean.parmMap['lastName']}"
requiredMessage="last name required"
size="95"
maxlength="95"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();return false;" >
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Birth Date:" for="birthDate"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="birthDate"
value="#{testBean.parmMap['birthDate']}"
requiredMessage="birth date required"
converter="dpConverter"
styleClass="datePicker"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(1).show();$(this).mask('99/99/9999');return false;">
<p:ajax event="change" process="#this" update="#this"/>
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Start Date:" for="startDate"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="startDate"
value="#{testBean.parmMap['startDate']}"
requiredMessage="start date required"
converter="dpConverter"
styleClass="datePicker"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(2).show();$(this).mask('99/99/9999');return false;">
<!-- optional to populate another field with same value...
onchange="$('...hashSymbolHere...queryForm\\:endDate').val($(this).val());">
-->
<p:ajax event="change" process="#this" update="#this"/>
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<p:commandButton
id="submit"
value="Submit"
oncomplete="applyDatePicker();"
type="submit"
update="#form"
process="#form"
action="#{testBean.submitQuery}"
style="width:150px;"
styleClass="button"/>
<p:commandButton
value="Reset"
update="#form"
onclick="location.reload();return true;"
process="#this"
actionListener="#{testBean.reset}"
immediate="true"
ajax="false"/>
</h:panelGroup>
</p:panel>
</h:form>
<h:outputStylesheet library="styles" name="query.css" />
<h:outputScript library="primefaces" name="/jquery/jquery.js" />
<h:outputScript library="primefaces" name="/jquery/plugins/ui/jquery-ui.custom.js" />
<h:outputScript library="primefaces" name="/jquery/plugins/inputmask/maskedinput.js" />
<h:outputScript library="js" name="index.js" target="head" />
</h:body>
</f:view>
</html>
index.js
$(document).ready(function()
{
applyDatePicker();
});
function applyDatePicker(){
$('.datePicker').datepicker(
{
showOn: 'button',
buttonText: "Choose",
showButtonPanel: true,
showOptions: {direction: 'up'},
changeYear: true,
changeMonth: true,
yearRange: "c-120:c+0"
});
}
TestBean.java
package aaa.bbb.ccc.war;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIForm;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component("testBean")
#Scope("request")
public class TestBean implements Serializable
{
public TestBean()
{
parmMap = this.getParmMap();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
}
public void reset(ActionEvent event)
{
LinkedHashMap<String, Object> m = new LinkedHashMap<String, Object>();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("parmMap");
setParmMap(m);
}
public String submitQuery()
{
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("hitlistData");
if (this.getParmMap().isEmpty())
{
return "";
}
return "/page2.xhtml?faces-redirect=true";
}
private static LinkedHashMap<String, Object> parmMap;
public LinkedHashMap<String, Object> getParmMap()
{
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("parmMap");
if (null == map)
{
map = new LinkedHashMap<String, Object>();
}
return map;
}
public void setParmMap(LinkedHashMap<String, Object> map)
{
parmMap = map;
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
}
private static SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
public void validate(ComponentSystemEvent e) throws ParseException
{
LinkedHashMap parmMap = this.getParmMap();
UIForm queryForm = (UIForm) e.getComponent();
FacesContext fc = FacesContext.getCurrentInstance();
UIInput lastName_c = (UIInput) queryForm.findComponent("lastName");
String lastName = (String) (lastName_c.getValue());
UIInput birthDate_c = (UIInput) queryForm.findComponent("birthDate");
String birthDate = (String) birthDate_c.getValue();
UIInput startDate_c = (UIInput) queryForm.findComponent("startDate");
String startDate = (String) startDate_c.getValue();
try
{
if (null != lastName && lastName.trim().length() > 0)
{
if (null == birthDate || birthDate.length() < 1)
{
birthDate_c.setValid(false);
fc.addMessage(birthDate_c.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, birthDate_c.getRequiredMessage(), birthDate_c.getRequiredMessage()));
}
else
{
birthDate_c.setValid(true);
}
}
else
{
birthDate_c.setValid(true);
}
if (null == startDate || startDate.trim().length() < 1)
{
startDate_c.setValid(false);
fc.addMessage(startDate_c.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, startDate_c.getRequiredMessage(), startDate_c.getRequiredMessage()));
}
else
{
startDate_c.setValid(true);
}
if (fc.getMessageList().size() > 0)
{
fc.renderResponse();
}
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
}
It's because you're returning false on focus here:
<p:inputText
...
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();return false;" >
</p:inputText>
Returning false causes the event's default behaviour to be blocked.
To fix your problem, simply remove return false; from onfocus attribute of the input component.
<p:inputText
...
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();" >
</p:inputText>
I have a managed bean placed in view scope. Here is the bean:
#ManagedBean(name = "adminController")
#ViewScoped
public class AdminController extends BaseWebController implements Serializable {
private static final long serialVersionUID = 1019716974557397635L;
private transient CustomerDTO customerDTO;
#PostConstruct
public void init() {
customerDTO = new CustomerDTO();
}
public void saveCustomer(ActionEvent event) {
System.out.println(customerDTO.isActive());
try {
getServiceProvider().getCustomerService().addNewCustomer(customerDTO);
getFacesContext().addMessage(null, FacesMessageUtils.getMessageForCustomerAddSuccess(getFacesContext()));
} catch (Throwable throwable) {
getFacesContext().addMessage(null, FacesMessageUtils.getMessageForCustomerAddError(getFacesContext()));
printStackTrace(throwable);
}
}
public CustomerDTO getCustomerDTO() {
return customerDTO;
}
public void setCustomerDTO(CustomerDTO customerDTO) {
this.customerDTO = customerDTO;
}
}
The view is:
<ui:composition 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"
xmlns:pe="http://primefaces.org/ui/extensions">
<p:panel header="#{adbBundle['admin.addCustomerPanel.header']}"
id="addCustomerPanel" toggleable="true">
<p:panelGrid columns="2" id="addCustomerTable"
styleClass="addCustomerTable">
<f:facet name="header">
<p:outputLabel id="header"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.header']}" />
</f:facet>
<p:outputLabel for="customerName"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerName']}" />
<h:panelGroup layout="block">
<p:inputText id="customerName" styleClass="customerName"
autocomplete="off"
label="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerName']}"
value="#{adminController.customerDTO.customerName}" required="true" />
<pe:tooltip for="customerName"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerName.tooltip']}"
showEffect="slideToggle" hideEffect="slideToggle" showDelay="0"
myPosition="left center" atPosition="right center" />
</h:panelGroup>
<p:outputLabel for="customerId"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerId']}" />
<h:panelGroup layout="block">
<p:inputText id="customerId" autocomplete="off"
label="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerId']}"
value="#{adminController.customerDTO.customerId}" required="true">
<f:validator validatorId="customerIDValidator" />
</p:inputText>
<pe:tooltip for="customerId"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.customerId.tooltip']}"
showEffect="slideToggle" hideEffect="slideToggle" showDelay="0"
myPosition="left center" atPosition="right center" />
</h:panelGroup>
<p:outputLabel for="activeStatus"
value="#{adbBundle['admin.addCustomerPanel.addCustomerTable.activeStatus']}" />
<h:panelGroup layout="block">
<p:selectBooleanCheckbox id="activeStatus" value="#{adminController.customerDTO.active}" />
</h:panelGroup>
<f:facet name="footer">
<p:commandButton value="#{adbBundle['saveButton']}"
actionListener="#{adminController.saveCustomer}"
icon="ui-icon-check" update=":growl, #form" />
</f:facet>
</p:panelGrid>
</p:panel>
</ui:composition>
The problem that I am facing is, after the actionListener successfully executed the input fields are holding the values.
The h:form is not visible in the aforementioned xhtml, it is placed in the parent page as:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/templates/globalTemplate.xhtml">
<ui:define name="title">#{adbBundle['home']}</ui:define>
<ui:define name="content">
<p:growl id="growl" showDetail="true" />
<h:form id="form">
<ui:include src="/WEB-INF/includes/addCustomer.xhtml" />
</h:form>
</ui:define>
</ui:composition>
However if I add customerDTO = new CustomerDTO(); at the end of the actionListener saveCustomer, the inputs are reset.
Is it the way to clear the form? Or there is a better way to achieve this?
To clear form data using ActionEvent on button
public void clear(){
customerDTO = new CustomerDTO();
}
In this page I,m going to let the user to make the password visible by clicking a checkbox. Actually two Inputs (password, conPassword) should hide and another input (passwordV) should be displayed. All these 3 inputs have the same value and needs to keep their values as user switches between these 2 states: (having two secret fields visible or having one plain text field)
I put the page and bean code here:
JSF Page:
<?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"
template="./templates/main_template.xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns="http://www.w3.org/1999/xhtml">
<ui:define name="subTitle">
:: #{lbls.newEntry} </ui:define>
<ui:define name="content">
<p:panel rendered="#{current.loggedIn}" header="#{lbls.newEntry}" >
<h:form id="frmEntry">
<h:panelGrid columns="3">
<h:panelGroup>
<h:outputLabel for="title" value="#{lbls.title}:"/>
<p:focus for="title"/>
</h:panelGroup>
<p:inputText id="title" value="#{entry.passwordEntry.title}" maxlength="100" label="#{lbls.title}" required="true"/>
<p:message for="title"/>
<h:outputLabel for="description" value="#{lbls.description}:"/>
<p:inputTextarea id="description" value="#{entry.passwordEntry.description}" maxlength="500" rows="3" cols="40" label="#{lbls.description}"/>
<p:message for="description"/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<h:outputLabel for="username" value="#{lbls.username}:"/>
<p:inputText id="username" value="#{entry.passwordEntry.username}" maxlength="100" label="#{lbls.username}"/>
<p:message for="username"/>
<h:outputLabel for="password" id="lblPassword" value="#{lbls.password}:" styleClass="#{entry.showPasswords ? 'none' : ''}" />
<p:password id="password" feedback="true" value="#{entry.passwordEntry.password}" match="conPassword" maxlength="100"
label="#{lbls.password}" promptLabel="#{lbls.strengthPromp}" weakLabel="#{lbls.weakPassword}"
goodLabel="#{lbls.goodPassword}" strongLabel="#{lbls.strongPassword}" styleClass="#{entry.showPasswords ? 'none' : ''}"
/>
<p:message id="msgPassword" for="password" class="#{entry.showPasswords ? 'none' : ''}"/>
<h:outputLabel id="lblConPassword" for="conPassword" value="#{lbls.conPassword}:"
styleClass="#{entry.showPasswords ? 'none' : ''}"/>
<p:password id="conPassword" value="#{entry.passwordEntry.password}" label="#{lbls.conPassword}" maxlength="100"
styleClass="#{entry.showPasswords ? 'none' : ''}"/>
<p:message id="msgConPassword" for="conPassword" class="display: #{!entry.showPasswords ? 'none' : ''}"/>
<h:outputLabel id="lblPasswordV" for="passwordV" value="#{lbls.password}:"
styleClass="#{!entry.showPasswords ? 'none' : ''}"/>
<p:inputText id="passwordV" value="#{entry.passwordEntry.password}" maxlength="100"
label="#{lbls.password}"
styleClass="#{!entry.showPasswords ? 'none' : ''}"/>
<p:message id="msgPasswordV" for="passwordV"
class="#{!entry.showPasswords ? 'none' : ''}"/>
<h:outputLabel for="showPasswords" value="#{lbls.showPasswords}:"/>
<p:selectBooleanCheckbox id="showPasswords" label="#{lbls.showPasswords}" value="#{entry.showPasswords}">
<p:ajax process="password passwordV conPassword" update="password passwordV conPassword lblPassword lblPasswordV lblConPassword msgPassword msgConPassword msgPasswordV"/>
</p:selectBooleanCheckbox>
<h:outputText/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<h:outputLabel for="url" value="#{lbls.url}:"/>
<p:inputText id="url" value="#{entry.passwordEntry.url}" maxlength="255" label="#{lbls.url}"/>
<p:message for="url"/>
<h:outputLabel for="ip" value="#{lbls.ip}:"/>
<p:inputText id="ip" value="#{entry.passwordEntry.ip}" maxlength="255" label="#{lbls.ip}"/>
<p:message for="ip"/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<h:outputLabel for="tags" value="#{lbls.tags}:"/>
<p:autoComplete id="tags" value="#{entry.selectedTags}"
completeMethod="#{entry.selectTag}" converter="PasswordEntry" multiple="true"
var="tag" itemLabel="#{tag.title}" itemValue="#{tag}" />
<p:message for="tags"/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<p:spacer height="10"/>
<h:outputText/>
<h:panelGroup layout="block" styleClass="right-align">
<p:commandButton value="#{lbls.save}" actionListener="#{entry.save(event)}"
update=":growl messages"/>
</h:panelGroup>
<f:facet name="footer">
<p:messages id="messages"/>
</f:facet>
</h:panelGrid>
</h:form>
</p:panel>
<ui:include src="/templates/not_logged_in.xhtml" rendered="!#{current.loggedIn}"/> </ui:define>
</ui:composition>
and Bean:
package package;
#ManagedBean(name = "entry")
#ViewScoped
public class PasswordEntryBean implements Serializable {
//<editor-fold defaultstate="collapsed" desc="FIELDS">
private static final Logger logger = LogUtil.getLogger(PasswordEntryBean.class);
private PasswordEntry passwordEntry;
#ManagedProperty(value = "#{current}")
private CurrentSessionBean current;
private Database database;
private List<PasswordTag> selectedTags = new ArrayList<PasswordTag>();
private Set<PasswordTag> tags;
private boolean showPasswords;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="CONSTRUCTORS">
public PasswordEntryBean() {
passwordEntry = new PasswordEntry();
}
#PostConstruct
public void init() {
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="PROPERTIES">
public PasswordEntry getPasswordEntry() {
return passwordEntry;
}
public Database getDatabase() {
return database;
}
public boolean getShowPasswords() {
return showPasswords;
}
public void setShowPasswords(boolean showPasswords) {
this.showPasswords = showPasswords;
}
public void setDatabase(Database database) {
this.database = database;
}
public Set<PasswordTag> getTags() {
return tags;
}
public void setTags(Set<PasswordTag> tags) {
this.tags = tags;
}
public List<PasswordTag> getSelectedTags() {
return selectedTags;
}
public void setSelectedTags(List<PasswordTag> selectedTags) {
this.selectedTags = selectedTags;
}
public void setPasswordEntry(PasswordEntry passwordEntry) {
this.passwordEntry = passwordEntry;
}
public CurrentSessionBean getCurrent() {
return current;
}
public void setCurrent(CurrentSessionBean current) {
this.current = current;
}
//</editor-fold>
}
UPDATED CODE
I just wrote a simpler code in order to make it easier for you to understand my problem:
JSF:
<?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:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Facelet Title</title>
<style type="text/css">
.none {
display: none;
}
</style>
</h:head>
<h:body>
<h1>Register</h1>
<h:form id="frmRegistration">
<h:panelGrid columns="3">
<h:outputLabel value="Username:" for="username"/>
<p:inputText label="username" id="username" value="#{testBean.username}" required="true"/>
<p:message for="username"/>
<h:outputLabel value="Password:" id="lblPassword" for="password" styleClass="#{!testBean.visiblePassword ? '' : 'none'}"/>
<p:password label="password" id="password" value="#{testBean.password}"
styleClass="#{!testBean.visiblePassword ? '' : 'none'}"/>
<p:message for="password" id="msgPassword" class="#{!testBean.visiblePassword ? '' : 'none'}"/>
<h:outputLabel value="Confirm Password:" id="lblCpassword" for="cpassword" styleClass="#{!testBean.visiblePassword ? '' : 'none'}"/>
<p:password label="confirm password" id="cpassword" value="#{testBean.password}"
styleClass="#{!testBean.visiblePassword ? '' : 'none'}"/>
<p:message for="cpassword" id="msgCpassword" class="#{!testBean.visiblePassword ? '' : 'none'}"/>
<h:outputLabel value="Password:" id="lblVpassword" for="vpassword" styleClass="#{testBean.visiblePassword ? '' : 'none'}"/>
<p:inputText label="password" id="vpassword" value="#{testBean.password}"
styleClass="#{testBean.visiblePassword ? '' : 'none'}"/>
<p:message for="vpassword" id="msgVpassword" class="#{testBean.visiblePassword ? '' : 'none'}"/>
<h:outputLabel value="Show password"/>
<p:selectBooleanButton value="#{testBean.visiblePassword}"
onLabel="Yes" offLabel="No">
<p:ajax update="messages password cpassword vpassword lblPassword lblCpassword lblVpassword msgPassword msgCpassword msgVpassword"
process="messages password cpassword vpassword" listener="#{testBean.addMessage}" />
</p:selectBooleanButton>
<f:facet name="footer">
<p:commandButton actionListener="#{testBean.save(event)}" value="Save" update="messages"/>
<p:messages id="messages"/>
</f:facet>
</h:panelGrid>
</h:form>
</h:body>
</html>
AND BEAN:
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
#ManagedBean
#ViewScoped
public class TestBean {
private String username;
private String password;
private boolean visiblePassword;
public void addMessage() {
String summary = visiblePassword ? "Checked" : "Unchecked";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(summary));
}
public TestBean() {
}
public void save(ActionEvent event) {
}
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 boolean isVisiblePassword() {
return visiblePassword;
}
public void setVisiblePassword(boolean visiblePassword) {
this.visiblePassword = visiblePassword;
}
}
This code can hide two fields and show the third field properly if I do not add process attribute to the <p:ajax tag. But this attribute is needed in order to these fields keep their values when the user switches between two modes (2 secret fields / 1 plain text field)
But it fails!
==========================================================
SECOND UPDATE
I used redisplay and the problem of empty values solved but still the inputs don't hide/show unless I set the update and process to #form which is not good for my case.
<?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:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Facelet Title</title>
<style type="text/css">
.none {
display: none;
}
</style>
</h:head>
<h:body>
<h1>Register</h1>
<h:form id="frmRegistration">
<h:panelGrid columns="3">
<h:outputLabel value="Username:" for="username"/>
<p:inputText label="username" id="username" value="#{testBean.username}" required="true"/>
<p:message for="username"/>
<h:outputLabel value="Password:" id="lblPassword" for="password" rendered="#{!testBean.visiblePassword}"/>
<p:password redisplay="true" label="password" id="password" value="#{testBean.password}"
rendered="#{!testBean.visiblePassword}"/>
<p:message for="password" id="msgPassword" rendered="#{!testBean.visiblePassword}"/>
<h:outputLabel value="Confirm Password:" id="lblCpassword" for="cpassword" rendered="#{!testBean.visiblePassword}"/>
<p:password redisplay="true" label="confirm password" id="cpassword" value="#{testBean.password}"
rendered="#{!testBean.visiblePassword}"/>
<p:message for="cpassword" id="msgCpassword" rendered="#{!testBean.visiblePassword}"/>
<h:outputLabel value="Password:" id="lblVpassword" for="vpassword" rendered="#{testBean.visiblePassword}"/>
<p:inputText label="password" id="vpassword" value="#{testBean.password}"
rendered="#{testBean.visiblePassword}"/>
<p:message for="vpassword" id="msgVpassword" rendered="#{testBean.visiblePassword}"/>
<h:outputLabel value="Show password"/>
<p:selectBooleanButton value="#{testBean.visiblePassword}"
onLabel="Yes" offLabel="No">
<p:ajax update="messages password cpassword vpassword lblPassword lblCpassword lblVpassword msgPassword msgCpassword msgVpassword"
process="password cpassword vpassword" listener="#{testBean.addMessage}" />
</p:selectBooleanButton>
<f:facet name="footer">
<p:commandButton actionListener="#{testBean.save(event)}" value="Save" update="messages"/>
<p:messages id="messages"/>
</f:facet>
</h:panelGrid>
</h:form>
</h:body>
</html>
Your main mistake is that you're toggling visibility of the input fields using CSS in the client side, not using JSF in the server side. So JSF basically never knows which one is shown/hidden. All it knows is that both fields are shown. So it will process the both fields. As you've bound the value of the both fields to the one and same property, it will always end up getting the value of the last processed field.
You need to show/hide the input fields using JSF in the server side instead. You can use the therefor provided rendered attribute.
rendered="#{testBean.visiblePassword}"
The problem is that you're binding the same variable entry.passwordEntry.password to 2 or more fields, so when submitting the <h:form> only one of the values in those fields will be set to entry.passwordEntry.password, the other values will be discarded.
The best way to solve this will be to have different variables for every field you have/need on the form. By looking at your code, it looks like that can be achieved by having 3 PasswordEntry attributes in your bean:
#ManagedBean(name = "entry")
#ViewScoped
public class PasswordEntryBean implements Serializable {
//other attributes...
private PasswordEntry passwordEntry;
private PasswordEntry passwordEntryV;
private PasswordEntry conPasswordEntry;
//<editor-fold defaultstate="collapsed" desc="CONSTRUCTORS">
public PasswordEntryBean() {
passwordEntry = new PasswordEntry();
passwordEntryV = new PasswordEntry();
conPasswordEntry = new PasswordEntry();
}
//getters and setters...
}
JSF Code:
<p:password id="password" feedback="true" value="#{entry.passwordEntry.password}"
match="conPassword" maxlength="100" label="#{lbls.password}"
promptLabel="#{lbls.strengthPromp}" weakLabel="#{lbls.weakPassword}"
goodLabel="#{lbls.goodPassword}" strongLabel="#{lbls.strongPassword}"
styleClass="#{entry.showPasswords ? 'none' : ''}" />
<p:password id="conPassword" value="#{entry.conPasswordEntry.password}"
label="#{lbls.conPassword}" maxlength="100"
styleClass="#{entry.showPasswords ? 'none' : ''}"/>
<p:inputText id="passwordV" value="#{entry.passwordEntryV.password}"
maxlength="100" label="#{lbls.password}"
styleClass="#{!entry.showPasswords ? 'none' : ''}"/>
If you want/need to have the same value in 2 or 3 places, you have to take into account that the bindings should not be in the same <h:form>, otherwise you will have the same problem. You can synchronize the variable values using plain JavaScript (after all, the <p:password> will be <input type="password"> and <p:input> will be <input type="text">) or in the server side when executing an action i.e. the listener that should be executed when selecting a value in your <p:selectBooleanCheckbox>.