The following is my code snippet in my abc.xhtml page :
<p:panelGrid id="pnlGrd_numOfLbl"
style="align:center; width:100%;" cellpadding="5">
<c:forEach var="i" begin="1" end="${specificationMB.numOfLbl}" >
<p:row>
<p:column width="50%">
<p:outputLabel value="Label ${i}" />
</p:column>
<p:column width="50%">
<p:inputText id="inputTxt_${i}" style="width:150px;" />
</p:column>
</p:row>
</c:forEach>
</panelGrid>
This is my panelGrid I am generating inputText dynamically depending
numOfLable. After generation say 2 will be generate user will add some
text to each inputText so my Question is How can I get value of dyanamically
generated inputbox.
Thanks.
This can easily be done with basics of JSF and primefaces. Here is full working Example:
XHTML File (I am using p:panel and ui:repeater)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<link rel=" stylesheet" type="text/css" href="css/style.css"></link>
</h:head>
<h:body>
<h:form>
<p:panel header="Panel">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.lbl} :" />
</p:column>
<p:column width="50%">
<p:inputText value="#{lbl.value}" />
</p:column>
</p:row>
</ui:repeat>
</p:panel>
<p:commandButton actionListener="#{tBean.submit}" value="Subtmi" update="values"></p:commandButton>
<p:outputPanel id="values">
<ui:repeat var="lbl" value="#{tBean.lblClassess}">
<p:row>
<p:column width="50%">
<p:outputLabel value="#{lbl.value} :" />
</p:column>
</p:row>
</ui:repeat>
</p:outputPanel>
</h:form>
</h:body>
</f:view>
<body>
</body>
</html>
Managed Bean
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
#ManagedBean(name = "tBean")
#ViewScoped
public class TestBean {
private List<LabelClass> lblClassess;
public TestBean() {
lblClassess = new ArrayList<LabelClass>();
lblClassess.add(new LabelClass("First Label", ""));
lblClassess.add(new LabelClass("Second Label", ""));
lblClassess.add(new LabelClass("Third Label", ""));
}
public void submit(ActionEvent e) {
for (LabelClass lbl : lblClassess) {
System.out.println(lbl.getValue());
}
}
public List<LabelClass> getLblClassess() {
return lblClassess;
}
public void setLblClassess(List<LabelClass> lblClassess) {
this.lblClassess = lblClassess;
}
}
Label Class
public class LabelClass {
private String lbl;
private String value;
public LabelClass(String lbl, String value) {
super();
this.lbl = lbl;
this.value = value;
}
public String getLbl() {
return lbl;
}
public void setLbl(String lbl) {
this.lbl = lbl;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Output
In order to get the values of your dynamically generated inputTexts. You may do something like this.
<input type="text" id="inputTxt_${i}" name="inputTxt_${i}" style="width:150px;" />
Then retrieve the text value by using this code in servlet
String inputText1 = request.getParameter("nameOfFirstInputText");
You can bind the value into the bean value object:
<input type="text" id="inputTxt_${i}" value="${specificationMB.getValue(i).value}" />
Related
first of all, I am writing this because I am desperate. The thing is I was doing a simple Spring Boot CRUD with Primefaces. I used a bean called "carBean" to access the data in the index.xhtml file. Until there everything ok, things started to turn weird from now on. I tried to use a simple inputText to bind a text given in the UI to a property in the bean.
But I was constantly getting error 500, telling me that the property "marca" was not found in the bean, and I have checked 10000 times and everything is OK in there. So I started testing, and eventually I figured out that, the property that was working fine "carBean.cars" if I change the name to whatever I change (and obviously the methods liked to the property), It stop working. Is like the only property that works has to be named "cars". What I am missing here? Is driving me crazy, I promise this was my last resource. Thanks in advance .
carBean
package com.example.bean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import com.example.controller.CarController;
import com.example.dto.CarDTO;
import lombok.Data;
#Data
#Named("carBean")
#Scope(value = "session")
public class CarBean implements Serializable {
private static final long serialVersionUID = -8338541378806874723L;
#Autowired
CarController carController;
private List<CarDTO> cars;
private Integer id;
private String marca;
private String modelo;
private String precio;
private String bastidor;
private String potencia;
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public List<CarDTO> getCars() {
cars = carController.getAllCars();
return cars;
}
public void delete(CarDTO car) {
carController.deleteCar(car.id);
cars = carController.getAllCars();
}
public void add() {
CarDTO newCar = new CarDTO();
newCar.marca = this.marca;
newCar.modelo = this.modelo;
newCar.precio = this.precio;
newCar.bastidor = this.bastidor;
newCar.potencia = this.potencia;
carController.create(newCar);
}
public String redirect() {
return "index.xhtml?faces-redirect=true";
}
}
index.xhtml
<!DOCTYPE xhtml 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:rich="http://richfaces.org/rich"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h3> REGISTRO DE COCHES </h3>
<h:form id = "tabla">
<div class="card">
<p:dataTable var="car" value="#{carBean.cars}">
<p:column sortBy="#{car.marca}" headerText="Marca">
<h:outputText value="#{car.marca}" />
</p:column>
<p:column sortBy="#{car.modelo}" headerText="Modelo">
<h:outputText value="#{car.modelo}" />
</p:column>
<p:column sortBy="#{car.precio}" headerText="Precio">
<h:outputText value="#{car.precio}" />
</p:column>
<p:column sortBy="#{car.bastidor}" headerText="Bastidor">
<h:outputText value="#{car.bastidor}" />
</p:column>
<p:column sortBy="#{car.potencia}" headerText="Potencia">
<h:outputText value="#{car.potencia}" />
</p:column>
<p:column>
<p:commandButton type="submit" value="Eliminar" actionListener="#{carBean.delete(car)}"
update=":tabla" />
<p:commandButton type="button" value="Editar"/>
</p:column>
</p:dataTable>
<p:commandButton value="Nuevo Coche" type="submit" oncomplete="PF('createModal').show();"/>
</div>
</h:form>
<p:dialog header="Agregar" widgetVar="createModal" id="createModal">
<h:form id="createDialog">
<p:panel header="Detalles del coche">
<h:panelGrid columns="1">
<h:outputLabel value="Marca:"/>
<h:inputText id="marca" value="#{carBean.marca}" required="true"> </h:inputText>
<h:outputLabel value="Modelo"/>
<h:inputText id="modelo"> </h:inputText>
<h:outputLabel value="Precio"/>
<h:inputText id="precio"> </h:inputText>
<h:outputLabel value="Bastidor"/>
<h:inputText id="bastidor"> </h:inputText>
<h:outputLabel value="Potencia"/>
<h:inputText id="potencia"> </h:inputText>
</h:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</h:head>
</html>
Why I cannot used other property that isn´t called "cars"?
Don't mess Lombok #Data autogenerated getters and setters with the one you've declared in the Bean.
You have used a getter as a method, which is not a good thing to do because it can be called multiple times, see: Why JSF calls getters multiple times
public List<CarDTO> getCars() {
cars = carController.getAllCars(); // remove business logic from getter
return cars;
}
Better initialize your private List<CarDTO> cars variable in a method annotated with #PostContruct
#PostConstruct
public void init() {
cars = carController.getAllCars();
}
For more check this example: PrimeFaces DataTable CRUD
I´ve a data table with primefaces, that has a filter column. So when I access my xhtml it doesn´t show the populated data till I enter values in the filter. Or if I take out the filter it shows the populated data.
Here is my managed bean code:
#ManagedBean(name="estatusAdminMB")
#ViewScoped
public class EstatusAdminManagedBean implements Serializable {
private IEstatusService estatusService;
private List<MapeoEstatusDTO> mapeoEstatusList = new ArrayList<MapeoEstatusDTO>();
private List<MapeoEstatusDTO> filteredPorMapeoEstatusDTO = new ArrayList<MapeoEstatusDTO>();
private MapeoEstatusDTO selectedMapeoEstatus = new MapeoEstatusDTO();
/**
* Creates a new instance of EstatusAdminManagedBean
*/
public EstatusAdminManagedBean() {
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
mensajeriasService = (IMensajeriasService) context.getBean("MensajeriasService");
originadoresService = (IOriginadoresService) context.getBean("OriginadoresService");
estatusService = (IEstatusService) context.getBean("EstatusService");
populateMapeo();
}
private void populateMapeo() {
try {
mapeoEstatusList.clear();
mapeoEstatusList.addAll(estatusService.getMapeoEstatus());
System.out.println(mapeoEstatusList.size());
} catch (ServiceException ex) {
Logger.getLogger(EstatusAdminManagedBean.class.getName()).log(Level.SEVERE, null, ex);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
"Ocurrió un error al cargar el mapeo."));
}
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Mapeo Seleccionado", ((MapeoEstatusDTO) event.getObject()).getCodigo().getDescripcion());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public IEstatusService getEstatusService() {
return estatusService;
}
public void setEstatusService(IEstatusService estatusService) {
this.estatusService = estatusService;
}
public MapeoEstatusDTO getSelectedMapeoEstatus() {
return selectedMapeoEstatus;
}
public void setSelectedMapeoEstatus(MapeoEstatusDTO selectedMapeoEstatus) {
this.selectedMapeoEstatus = selectedMapeoEstatus;
}
public List<MapeoEstatusDTO> getFilteredPorMapeoEstatusDTO() {
return filteredPorMapeoEstatusDTO;
}
public void setFilteredPorMapeoEstatusDTO(List<MapeoEstatusDTO> filteredPorMapeoEstatusDTO) {
this.filteredPorMapeoEstatusDTO = filteredPorMapeoEstatusDTO;
}
}
and here is my xhtml code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US"
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"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:body>
<ui:composition template="../template/Layout.xhtml">
<ui:define name="content">
<div class="frame">
<h:form id="mapeoForm">
<p:growl id="growl" showDetail="true" />
<p:spacer> </p:spacer>
<div style="text-align:center">
<h:outputText value="Mapeo de Estatus" />
</div>
<p:spacer> </p:spacer>
<div align="center">
<p:dataTable id="mapeoTable" var="c" value="#{estatusAdminMB.mapeoEstatusList}" paginator="true" rows="10"
selection="#{estatusAdminMB.selectedMapeoEstatus}" selectionMode="single"
filteredValue="#{estatusAdminMB.filteredPorMapeoEstatusDTO}"
emptyMessage="No hay registros" rowKey="#{c.idMapeo}" rowIndexVar="rowIndex">
<p:ajax event="rowSelect" listener="#{estatusAdminMB.onRowSelect}"
update=":mapeoForm:dialogUpdate, :mapeoForm:growl"
oncomplete="dialogUpdateW.show()"/>
<f:facet name="header">
Haz clic sobre cualquier registro para editar
</f:facet>
<p:column id="originadorColumn" filterBy="#{c.originadorDTO.nombre}"
headerText="Originador" filterMatchMode="contains">
<h:outputText value="#{c.originadorDTO.nombre}" />
</p:column>
<p:column headerText="Descripción Estatus Folio">
#{c.estatus.descripcion}
</p:column>
<p:column headerText="Descripción Tipificación">
#{c.tipificacion.DESCRIPCION_TIPIFICACION}
</p:column>
<p:column headerText="Descripción Estatus Geotracking">
#{c.codigo.descripcion}
</p:column>
</p:dataTable>
<p:dialog maximizable="true" minHeight="400" minWidth="400" style="overflow-y:auto; top:5px; bottom:5px;"
id="dialogUpdate" header="Editar Mapeo" widgetVar="dialogUpdateW" resizable="false"
showEffect="fade" hideEffect="explode">
<h:form id="updateMapForm">
<table id="display">
</table>
</h:form>
</p:dialog>
</div>
</h:form>
</div>
</ui:define>
</ui:composition>
</h:body>
</html>
Why am I not getting the data from the very begging???
Thanks for the help.
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.
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>.
I have a datatable with each row having Edit and Delete buttons.
It is almost similar to http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionByColumn.jsf datatable.
When I click on Edit button, if I display the selected row values using <h:outputText> the values are being displayed properly.
But If I want to display it in a input text field using <h:inputText value="#{userCRUDMB.selectedUser.userName}"/> it is throwing error saying selectedUser is resolved as null.
If I only use <h:outputText ...> then userCRUDMB.selectedUser() method is getting called properly.
But If I use <h:inputText ...> in the Dialog, the setter method is not at all getting called.
I am using Mojarra 2.1.6, PrimeFaces 3.0, Apache Tomcat7.0.32.
Any idea why it is happening?
Code: Code is same as http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionByColumn.jsf, except in the dialogue box instead of displaying the text using I am trying to display in input textbox using .
public class User
{
private Integer userId;
private String userName;
private String password;
private String firstname;
private String lastname;
private String email;
private Date dob;
private String gender;
//setters/getters
}
package com.sivalabs.primefacesdemo.managedbeans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.sivalabs.primefacesdemo.model.User;
import com.sivalabs.primefacesdemo.model.UserDataModel;
import com.sivalabs.primefacesdemo.service.SpringContainer;
import com.sivalabs.primefacesdemo.service.UserService;
#ManagedBean(name="UserCRUDMB")
#RequestScoped
public class UserCRUDMB
{
private UserDataModel userDataModel;
private User selectedUser;
private User[] selectedUsers;
public UserCRUDMB()
{
List<User> users = new ArrayList<User>();
for (int i = 0; i < 15; i++) {
User user = new User();
user.setUserId(i);
user.setUserName("userName"+i);
users.add(user);
}
this.userDataModel = new UserDataModel(users);
}
public UserDataModel getUserDataModel() {
return userDataModel;
}
public void setUserDataModel(UserDataModel userDataModel) {
this.userDataModel = userDataModel;
}
public User[] getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(User[] selectedUsers) {
this.selectedUsers = selectedUsers;
}
public User getSelectedUser() {
System.out.println("get-->"+selectedUser);
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
System.out.println("set--->"+selectedUser);
this.selectedUser = selectedUser;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<body>
<h:form id="form">
<h:outputText value="PrimeFaces Demo - ShowUsers" />
<p:dataTable value="#{UserCRUDMB.userDataModel}" var="userObj"
selection="#{UserCRUDMB.selectedUsers}"
widgetVar="usersTbl">
<f:facet name="header">UserManagement</f:facet>
<p:column selectionMode="multiple"></p:column>
<p:column headerText="UserId">#{userObj.userId}</p:column>
<p:column headerText="UserName">#{userObj.userName}</p:column>
<p:column>
<p:commandButton value="Edit"
oncomplete="userEditDlg.show()"
update="form:userEditTbl">
<f:setPropertyActionListener target="#{UserCRUDMB.selectedUser}" value="#{userObj}"></f:setPropertyActionListener>
</p:commandButton>
</p:column>
<p:column>
<p:commandButton value="Delete" action="#{UserCRUDMB.deleteUser}"
update="usersTbl"
ajax="true">
<f:setPropertyActionListener target="#{UserCRUDMB.selectedUser}" value="#{userObj}"></f:setPropertyActionListener>
</p:commandButton>
</p:column>
<f:facet name="footer">
<p:commandButton value="Delete Selected" action="#{UserCRUDMB.deleteUsers}"
update="usersTbl"
ajax="true">
</p:commandButton>
</f:facet>
</p:dataTable>
<p:dialog widgetVar="userEditDlg" header="User Edit Form" hideEffect="explode"
minHeight="200" minWidth="300">
<h:panelGrid columns="2" id="userEditTbl" >
<h:outputLabel value="UserId" />
<h:outputText value="#{UserCRUDMB.selectedUser.userId}"/>
<h:outputLabel value="UserName" />
<h:inutText value="#{UserCRUDMB.selectedUser.userName}"/>
</h:panelGrid>
</p:dialog>
</h:form>
</body>
</html>
Thanks,
Siva
If you are using ajax, the request scope ist not the "ideal" scope since the bean will be recreated for each request. This can be the reason that selectedUser is null. Use the view scope (#ViewScoped) instead.