Load value from database to <h:inputText> with <h:selectOneMenu> valueChangeEvent - jsf-2

I want to develop a JSF Page which lets user edit a Employee from database. I loaded list of all employees in h:selectOneMenu. and second thing i want that with valueChangeEvent employee detail should be loaded in corresponding h:inputText. but nothing happens with every valueChangeEvent. So, where is the problem in codes.
<?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://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<div id="hdr">
<h1>Vinweb Services</h1>
<hr/>
</div>
;
<div id="mnu" style="height: 50px; width: auto; background: skyblue;">
<h:form>
<h:commandLink value="Home" action="index"/>
<h:outputText value=" "/>
<h:commandLink value="Create" action="create"/>
<h:outputText value=" "/>
<h:commandLink value="View" action="view"/>
<h:outputText value=" "/>
<h:commandLink value="Edit" action="edit"/>
</h:form>
</div>
<div id="cnt">
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Select an Employee"/>
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
<h:outputLabel value="Employee Code"/>
<h:inputText value="#{esb.empCode}" required="true"/>
<h:outputLabel value="Employee Name"/>
<h:inputText value="#{esb.empName}" required="true"/>
<h:outputLabel value="Joining Date"/>
<h:inputText value="#{esb.joinDate}" required="true">
<f:convertDateTime pattern="MM/yy"/>
</h:inputText>
<h:outputLabel value="Salary"/>
<h:inputText value="#{esb.salary}" required="true"/>
<h:commandButton value="Update" action="#{esb.updateEmployeeDetail}"/>
</h:panelGrid>
</h:form>
</div>
</h:body>
</html>
Backing Bean:
package ems.bean;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import javax.annotation.Resource;
import javax.faces.event.ValueChangeEvent;
import javax.sql.DataSource;
#Named(value = "esb")
#SessionScoped
public class EmployeeServiceBean implements Serializable {
#Resource(name = "JPA4A")
private DataSource ds;
// Member Declaration
private String empCode;
private String empName;
private Date joinDate;
private long salary;
private ArrayList empList;
// Service Code Segment
// This method will publish all emloyees in table to selectOneMenu
public ArrayList getEmployeeList() throws SQLException{
empList = new ArrayList();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
ResultSet rslt = stmt.executeQuery("SELECT empName FROM Employee");
while(rslt.next()){
empList.add(rslt.getString("empName"));
}
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
return empList;
}
// This method should load selected empoyee's details in inputText fields
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
String qry = "SELECT * FROM Employee WHERE empName = '"+emp+"'";
ResultSet rslt = stmt.executeQuery(qry);
rslt.next();
this.empCode = rslt.getString("empCode");
this.empName = rslt.getString("empName");
this.joinDate = rslt.getDate("joinDate");
this.salary = rslt.getLong("salary");
}
catch(SQLException se) {
se.printStackTrace();
}
finally{
con.close();
}
}
public void updateEmployeeDetail() throws SQLException{
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
boolean rs = stmt.execute("UPDATE Employee SET empCode='"+empCode+"', empName='"+empName+"', joinDate='"+joinDate+"', salary="+salary);
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
}
// Property Getter & Setter code segment
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}

The valueChangeListener is the wrong tool for the job.
You're here doing a onchange="submit()" which submits the entire form, including those required fields which in turn caused validation errors which in turn failed to reach your attention because you don't have any <h:message(s)> for them. If you have placed a <h:messages/> inside the form, or have paid more love and attention to server logs, you should have been notified of those required="true" validation errors.
You need <f:ajax listener>.
Replace
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
by
<h:selectOneMenu value="#{esb.empName}">
<f:selectItems value="#{esb.employeeList}"/>
<f:ajax listener="#{esb.loadEmployeeDetail}" render="#form" />
</h:selectOneMenu>
and replace
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
// ...
}
by
public void loadEmployeeDetail() throws SQLException{
String emp = empName; // You can also just use `empName` directly.
// ...
}
See also:
When to use valueChangeListener or f:ajax listener?

Related

Target Unreachable, identifier 'regionMaster' resolved to null

I created a managedBean & .xhtml page.It works fine on jsf 2.1 but not working on jsf 2.2 .Showing error Target Unreachable, identifier 'regionMaster' resolved to null
<!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:prime="http://primefaces.org/ui">
<head>
</head>
<ui:composition>
<h:form id="regionMaster" name="regionMaster">
<div id="region">
<table align="center">
<tr>
<td><prime:panel header="Region">
<prime:messages autoUpdate="true" />
<prime:panelGrid style="margin-top:20px">
<prime:row>
<prime:column>
<h:outputLabel for="txtRegionID" value="RegionID" />
</prime:column>
<prime:column colspan="3">
<prime:inputText id="txtRegionID" value="#{regionMaster.regionId}"
label="Region ID" required="true" />
</prime:column>
<prime:column>
<!-- <h:commandButton id="openPopUp" value="..."
target="RegionList.xhtml"
onclick="window.open('RegionList.xhtml','childWindow','status=no,toolbar=no,location=no,menubar=no,resizable = no,width=1008,height=390,scrollbars,left=100,top=50');"
action="#{regionList.xhtml}" />-->
<!-- <prime:commandButton value="View" icon="ui-icon-extlink"
actionListener="#{regionMaster.regionList}" validateClient="false" immediate="true" />-->
<prime:dialog id="basicDialog" header="Basic Dialog"
widgetVar="dlg1">
<h:outputText value="Resistance to PrimeFaces is futile!" />
</prime:dialog>
<prime:commandButton id="basic" value="Basic"
onclick="PF('dlg1').show();" type="button" />
</prime:column>
</prime:row>
<prime:row>
<prime:column>
<h:outputLabel for="txtRegionName" value="RegionName" />
</prime:column>
<prime:column colspan="3">
<prime:inputText id="txtRegionName" value="#{regionMaster.regionName}"
label="Region Name" required="true" />
</prime:column>
</prime:row>
<prime:row>
<prime:column>
</prime:column>
<prime:column colspan="1">
<prime:commandButton action="#{regionMaster.save}"
value="save" />
</prime:column>
<prime:column colspan="1">
<prime:commandButton accesskey="R" alt="Click to Reset"
validateClient="false" immediate="true"
action="#{regionMaster.reset}" value="Reset" />
</prime:column>
<prime:column colspan="1">
<prime:commandButton accesskey="D"
onclick="if (!confirm('Are you sure you want to delete?')) return false"
alt="Click to Delete" actionListener="#{regionMaster.delete}"
validateClient="false" immediate="true" value="delete">
</prime:commandButton>
</prime:column>
</prime:row>
</prime:panelGrid>
</prime:panel></td>
</tr>
</table>
</div>
</h:form>
</ui:composition>
</html>
MyBean is
package com.sst.cms.web.beans;
import javax.faces.bean.RequestScoped;
import org.primefaces.context.RequestContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.inject.Named;
#ManagedBean(name="regionMaster",eager=false)
#SessionScoped
#Named("regionMaster")
public class RegionMasterBean implements Serializable {
//private static final FacesMessage RegionList = null;
public RegionMasterBean() {
}
private String regionId;
private String regionName;
private String createdBy;
private Date createdDate;
private String modifiedBy;
private Date modifiedDate;
private String entity;
private ArrayList<RegionMasterBean> regionList;
public String getRegionId() {
System.out.println("Region id======"+regionId);
return regionId;
}
public void setRegionId(String regionId) {
System.out.println("Region id======"+regionId);
this.regionId = regionId;
}
// other getter+setter
public String save(){
System.out.println("Bean is calleddddddddd");
return "SUCCESSFUL";
}
public void reset(){
this.regionId = "";
this.regionName = "";
}
public String delete(){
return "Sucess";
}
// public String setId(){
// System.out.println("Region iddddddddddddd");
//
// FacesContext fc = FacesContext.getCurrentInstance();
// this.regionId = getCountryParam(fc);
//
// return regionId;
// }
//
public ArrayList<RegionMasterBean> regionListLoad(){
regionList = new ArrayList<RegionMasterBean>();
RegionMasterBean dto = new RegionMasterBean();
dto.setRegionId("REG001");
dto.setRegionName("India");
RegionMasterBean dto1 = new RegionMasterBean();
dto1.setRegionId("REG002");
dto1.setRegionName("Afganisthan");
regionList.add(dto);
regionList.add(dto1);
return regionList;
}
public ArrayList<RegionMasterBean> getRegionList() {
return regionList;
}
public void setRegionList(ArrayList<RegionMasterBean> regionList) {
this.regionList = regionList;
}
public String saveSetting(){
System.out.println("this is calleddddddd");
this.regionId = "Roo1";
return regionId;
}
#PostConstruct
public void regionList() {
System.out.println("region list is calledddddddd");
RequestContext.getCurrentInstance().openDialog("RegionList");
System.out.println("region list is calledddddddd");
}
}
It works fine with the project where i have jsf 1.2 but when i add this to a new project with jsf 2.2 it shows the error

getting the data on same browser window on click of row using primefaces or jsf

i am new on prime faces .I have a user with some attribute i have shown the table of user data . Now the requirement is that, on click of particular user row the data associated with that user must be shown on same window under the table please tell the way to do this i m trying to use layout but the problem is how i can get the data on same window .Give me learing site link if possible doing the same thing or tell me the procedure thanks
package com.poc.faces;
import java.util.Collection;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean
#ViewScoped
public class UserManagedBean {
UserService service = new UserService();
private String username;
private String password;
private String searchUser;
private Collection<User> searchUsersResults;
private User selectedUser;
public UserService getService() {
return service;
}
public void setService(UserService service) {
this.service = service;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSearchUser() {
return searchUser;
}
public void setSearchUser(String searchUser) {
this.searchUser = searchUser;
}
public Collection<User> getSearchUsersResults() {
return searchUsersResults = service.getAllUser();
}
public void setSearchUsersResults(Collection<User> searchUsersResults) {
this.searchUsersResults = searchUsersResults;
}
public User getSelectedUser() {
return selectedUser;
}
public String login() {
if ("sas".equalsIgnoreCase(getUsername())
&& "sas".equals(getPassword())) {
return "home";
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage(
"Invalid UserName and Password"));
return "login";
}
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("User Selected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Car Unselected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This home.xhtml
where i am getting the tabledata
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<link href="../css/style.css" type="text/css" rel="stylesheet" />
</h:head>
<h:body>
<p:layout style="min-width:400px;min-height:200px;" id="layout">
<p:layoutUnit position="center">
<h:form prependId="false">
<h:panelGroup layout="block" id="left_column"
style="width: 2px; left: 2px; margin-left: 2px">
<center>
<H1>UserData</H1>
<br />
<p:dataTable value="#{userManagedBean.searchUsersResults}"
var="user" pagination="true" rows="5" styleClass="userTable"
headerClass="userTableHeader"
rowClasses="userTableOddRow,userTableEvenRow"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<!-- <p:ajax event="rowSelect" listener="#{userManagedBean.onRowSelect}"
update=":form:display :form:growl" oncomplete="carDialog.show()" />
<p:ajax event="rowUnselect"
listener="#{userManagedBean.onRowUnselect}" update=":form:growl" /> -->
<p:column>
<f:facet name="header">UserId</f:facet>
<h:outputText value="#{user.userId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Username</f:facet>
<h:outputText value="#{user.username}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">EmailId</f:facet>
<h:outputText value=" #{user.emailId}"></h:outputText>
</p:column>
<p:column>
<f:facet name="header">Phone</f:facet>
<h:outputText value=" #{user.phone}"></h:outputText>
</p:column>
</p:dataTable>
</center>
</h:panelGroup>
</h:form>
<p:layoutUnit position="west" resizable="true" size="100"
minSize="40" maxSize="200">
West
</p:layoutUnit>
</p:layout>
</h:body>
</html>
I don't think there is a component of PF called layoutUnit. are you sure it's not layout?

setPropertyActionListener not working properly [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
primefaces selectOneMenu doesn’t working when it should
my setPropertyActionListener is not setting the corresponding bean property. I need to get the select public after i click the corresponding delete button (cbViewExcluir) which shows a confirm dialog before delete. Below is my xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="./../../resources/templates/baseTemplate.xhtml">
<ui:define name="content">
<f:view id="vRoot">
<p:fieldset legend="Manage publics">
<h:form id="frmPublics">
<!-- Global messages -->
<p:growl id="gMessages" sticky="false" globalOnly="true" />
<!-- Public list on dataTable -->
<p:dataTable id="dtPublics"
value="#{publicBean.lstPublics}"
paginator="true" rows="5"
rowsPerPageTemplate="5,10"
paginatorPosition="bottom"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
var="actual">
<f:facet name="header">
<p:commandButton id="cbViewNew" value="New" type="button" onclick="dlgNew.show();" />
</f:facet>
<!-- Colunas de edição e exclusão -->
<p:column>
<f:facet name="header">
<h:outputLabel value="Edit"/>
</f:facet>
<p:commandButton id="cbViewEdit"
image="ui-icon-pencil"
title="Edit"
update=":frmEdit:pEditPublic"
oncomplete="dlgEdit.show();">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
<h:outputLabel value="Delete"/>
</f:facet>
<p:commandButton id="cbViewDelete" onclick="dlgDelete.show();"
icon="ui-icon-close" title="Delete">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
<h:outputLabel id="olViewPublicName" value="#{actual.publicName}"/>
</p:column>
<p:column>
<f:facet name="header">
Public Type
</f:facet>
<h:outputLabel id="olViewPublicType" value="#{actual.publicType}"/>
</p:column>
</p:dataTable>
</h:form>
<!-- New dialog -->
<p:dialog id="dlgNewPublic" widgetVar="dlgNew" modal="true" header="New Public"
resizable="false">
<h:form id="frmNew">
<p:panel id="pNewPublico">
<p:messages id="mNewMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olNewPublicName" value="Name:" for="itNewPublicName"/>
<p:inputText id="itNewPublicName" value="#{publicBean.name}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olNewPublicType" for="somNewPublicType" value="Public type:"/>
<p:selectOneMenu id="somNewPublicType" value="#{publicBean.publicType}" effect="fade"
converter="#{publicBean.converter}"
required="true" requiredMessage="Enter the public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}" var="actual" itemLabel="#{actual.label}" itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgNew.hide()"/>
<p:commandButton id="cbSaveNew" value="Save"
actionListener="#{publicBean.save}"
oncomplete="handleSave(xhr, status, args);"
update=":frmPublics:dtPublics :frmNew :frmPublics:gMessages"
ajax="true"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
<!-- Delete dialog -->
<p:confirmDialog id="dialogDelete" message="Are you sure?"
header="Delete public" severity="alert"
widgetVar="dlgDelete">
<h:form id="frmDelete">
<p:commandButton id="cbDeleteCancel" value="Cancel" onclick="dlgDelete.hide()" type="button" />
<p:commandButton id="cbDeleteContinue" value="Continue"
update=":frmPublics:dtPublics :frmPublics:gMessages"
oncomplete="dlgDelete.hide()"
actionListener="#{publicBean.delete}"/>
</h:form>
</p:confirmDialog>
<!-- Edit dialog -->
<p:dialog id="dialogEdit" widgetVar="dlgEdit" header="Edit public"
resizable="false" modal="true">
<h:form id="frmEdit">
<p:panel id="pEditPublic">
<p:messages id="mEditMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olEditPublicName" value="Name:" for="itEditPublicName"/>
<p:inputText id="itEditPublicName" value="#{publicBean.selectedPublic.publicName}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olEditPublicType" for="somEditPublicType" value="Public type:"/>
<p:selectOneMenu id="somEditPublicType"
value="#{publicBean.selectedPublic.publicType}"
effect="fade"
converter="#{publicBean.converter}"
required="true"
requiredMessage="Select a public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}"
var="actual"
itemLabel="#{actual.label}"
itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgEdit.hide()"/>
<p:commandButton id="cbEditSave" value="Save"
actionListener="#{publicBean.alter}"
oncomplete="dlgEdit.hide();"
update=":frmPublics :frmEdit"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</p:fieldset>
</f:view>
<!-- Javascript callbacks -->
<script type="text/javascript">
function handleSaved(xhr, status, args){
if(args.saved){
dlgNew.hide();
}
}
function handleEdited(xhr, status, args){
if(args.edited){
dlgEdit.hide();
}
}
</script>
</ui:define>
And my bean is as follows:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.siseventos.managed;
import br.siseventos.dao.da.PublicoDAO;
import br.siseventos.dao.da.TipoPublicoDAO;
import br.siseventos.model.TbPublico;
import br.siseventos.model.TdTipoPublico;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "publicoBean")
#SessionScoped
public class PublicoBean {
// Campos
private TipoPublicoDAO daoTipoPublico = null;
private PublicoDAO daoPublico = null;
private String nome;
private List<SelectItem> lstMenuTipoPublico = new ArrayList<SelectItem>();
private TdTipoPublico tipoPublicoSelecionado = null;
private List<TbPublico> lstDataTablePublico = null;
private TbPublico publicoSelecionado;
// Util
private int maximoLinhasTablePublico = 5;
private boolean mostrarMsg = false;
// Construtor
public PublicoBean() {
// Inicializando as daos
daoPublico = new PublicoDAO();
daoTipoPublico = new TipoPublicoDAO();
// Carregando o datatable de publicos
lstDataTablePublico = daoPublico.consultarTodos();
// Carregando o menu de tipos de público
List<TdTipoPublico> l = getDaoTipoPublico().consultarTodos();
Iterator<TdTipoPublico> i = l.iterator();
while (i.hasNext()) {
TdTipoPublico atual = (TdTipoPublico) i.next();
lstMenuTipoPublico.add(new SelectItem(atual, atual.getNmeTipoPublico()));
}
}
public TipoPublicoDAO getDaoTipoPublico() {
return daoTipoPublico;
}
public void setDaoTipoPublico(TipoPublicoDAO daoTipoPublico) {
this.daoTipoPublico = daoTipoPublico;
}
public PublicoDAO getDaoPublico() {
return daoPublico;
}
public void setDaoPublico(PublicoDAO daoPublico) {
this.daoPublico = daoPublico;
}
// Getters e Setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<SelectItem> getLstMenuTipoPublico() {
return lstMenuTipoPublico;
}
public void setLstMenuTipoPublico(List<SelectItem> lstMenuTipoPublico) {
this.lstMenuTipoPublico = lstMenuTipoPublico;
}
public TdTipoPublico getTipoPublicoSelecionado() {
return tipoPublicoSelecionado;
}
public void setTipoPublicoSelecionado(TdTipoPublico tipoPublicoSelecionado) {
this.tipoPublicoSelecionado = tipoPublicoSelecionado;
}
public List<TbPublico> getLstDataTablePublico() {
return lstDataTablePublico;
}
public void setLstDataTablePublico(List<TbPublico> lstDataTablePublico) {
this.lstDataTablePublico = lstDataTablePublico;
}
public int getMaximoLinhasTablePublico() {
return maximoLinhasTablePublico;
}
public void setMaximoLinhasTablePublico(int maximoLinhasTablePublico) {
this.maximoLinhasTablePublico = maximoLinhasTablePublico;
}
public boolean isMostrarMsg() {
return mostrarMsg;
}
public void setMostrarMsg(boolean mostrarMsg) {
this.mostrarMsg = mostrarMsg;
}
public TbPublico getPublicoSelecionado() {
return publicoSelecionado;
}
public void setPublicoSelecionado(TbPublico publicoSelecionado) {
this.publicoSelecionado = publicoSelecionado;
}
// Actions e listeners
public void cadastrarPublico(ActionEvent ex) {
FacesContext contexto = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage();
try {
TbPublico p = new TbPublico();
p.setNmePublico(getNome());
p.setTdTipoPublico(getTipoPublicoSelecionado());
getDaoPublico().incluir(p);
// Carregar a lista de publicos novamente
lstDataTablePublico = getDaoPublico().consultarTodos();
// Mostrando msg de sucesso!
msg.setSummary("Público cadastrado com sucesso!");
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
// Invocando script no cliente
RequestContext rc = RequestContext.getCurrentInstance();
rc.addCallbackParam("salvo", true);
} catch (Exception e) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}
}
public void excluirPublico(ActionEvent e) {
FacesMessage msg = new FacesMessage();
FacesContext contexto = FacesContext.getCurrentInstance();
// Mostrando msg de sucesso!
msg.setSummary(publicoSelecionado.getNmePublico());
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
/*try {
// Excluindo o publico selecionado
daoPublico.excluir(getPublicoSelecionado().getIdtPublico());
} catch (Exception ex) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}*/
}
public void alterarPublico() {
FacesMessage msg = new FacesMessage("Publico alterado!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
// Converters
public Converter getConversor() {
return new Converter() {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Transformar string em objeto
TdTipoPublico r = null;
try {
r = getDaoTipoPublico().consultarPorIdt(Integer.parseInt(value));
} catch (NumberFormatException e) {
}
return r;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Transformar objeto em string
String r = null;
if (value instanceof TdTipoPublico) {
r = ((TdTipoPublico) value).getIdtTipoPublico().toString();
}
return r;
}
};
}
}
There is something i'm doing wrong?
its because of the attribute type="button" which is not firing the actionlistener.
when you declare this attribute (type="button") its not a p:commandButton anymore.
type="button" is push button purposes, it does not do any action or submit the form
try to remove type="button" attribute. it'd fire the actionlistener.
<p:commandButton id="cbViewExcluir"
image="ui-icon-circle-close"
onclick="dlgExcluir.show()"
title="Excluir"
update=":frmExcluir">
<!-- This is not working properly -->
<f:setPropertyActionListener value="#{atual}" target="# {publicoBean.publicoSelecionado}" />
</p:commandButton>
lemme know if this helps :)

inputText validator doesn't display error message

I have a simple form that get code then display his libelle, I added a validator bean that check if the code exist.
My problem is I can't display the error message whith when the code doesn't exist.
Here is the code:
test.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">
<h:head><title>Test</title>
</h:head>
<body class="bodyMain">
<h:form>
<h:panelGrid columns="3">
<h:outputText value="Code: " />
<h:inputText id="code" value="#{myBean.code}"
validator="#{myBean.validateCode}">
<f:ajax execute="#this" render="libelle" listener="#{myBean.setLibelle()}"/>
</h:inputText>
<h:message for="code" style="color:red"/>
</h:panelGrid>
<h:panelGrid id="libelle" columns="2">
<h:outputText value="Libelle: " />
<h:outputText value="#{myBean.libelle}" />
</h:panelGrid>
</h:form>
</body>
</html>
MyBean.java
#ManagedBean
#ViewScoped
public class MyBean implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private String code="";
private String libelle="";
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code=code;
}
public String getLibelle() {
return this.libelle;
}
public void setLibelle(String libelle) {
this.libelle=libelle;
}
public void setLibelle() {
if (code.compareTo("1")==0)
libelle="One";
else
libelle="";
}
public void validateCode(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
String code = (String)value;
if (code.compareTo("1") != 0) {
FacesMessage message = new FacesMessage("Code doesn't exist");
throw new ValidatorException(message);
}
}
}
Thank you for your help to resolve this problem
You're not updating the <h:message> component by the <f:ajax>. You need to give the <h:message> an id and include it in the <f:ajax render>.
<h:inputText id="code" value="#{myBean.code}" validator="#{myBean.validateCode}">
<f:ajax execute="#this" render="libelle codeMessage" listener="#{myBean.setLibelle()}"/>
</h:inputText>
<h:message id="codeMessage" for="code" style="color:red"/>
Unrelated to the concrete problem, don't initialize properties to empty strings. Let them by default null. Also, comparing objects should be done with equals() method, not with compareTo(). Finally, using a dropdown list with all available values instead of an input field would be more user friendly.

valueChangeListener is not getting called from <h:selectOneRadio> which is placed in side a <h:panelGrid>

I am facing an issue with h:selectOneRadio's valueChangeListener="#{user.loadYesNo}"
(I use Mojarra 2-0-8 on Tomcat-7) .
If I remove both the panelGrid enclosing the 'h:selectOneRadio', then the value change litener is getting fired.
View:
<!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">
<h:head><title> Starting JSF</title></h:head>
<h:body>
<h:form>
<h:panelGrid column="2">
<h:outputLabel>User Name</h:outputLabel>
<h:inputText id="loginName" value="#{user.userName}"></h:inputText>
<h:outputLabel>Password</h:outputLabel>
<h:inputSecret id="loginPassword" value="#{user.password}"></h:inputSecret>
</h:panelGrid>
<h:commandButton value="Submit" action ="#{user.validateLogin}">
<f:ajax execute="#form" render="yesNoRadioGrid message"></f:ajax>
</h:commandButton>
<h:panelGrid>
<h:outputText id ="message" value="#{user.message}"></h:outputText>
</h:panelGrid>
<h:panelGrid id="yesNoRadioGrid">
<h:panelGrid columns="2" rendered="#{user.yesNoRadioGridFlag}">
<h:outputText id ="otherLbl" value="Select Yes or No"></h:outputText>
<h:selectOneRadio id="yesNoRadio" value ="#{user.yesNoRadio}" valueChangeListener="#{user.loadYesNo}">
<f:selectItem itemValue="1" itemLabel="YES"></f:selectItem>
<f:selectItem itemValue="0" itemLabel="NO"></f:selectItem>
<f:ajax event="change" execute="#form" render="userDetailsGrid "></f:ajax>
</h:selectOneRadio>
</h:panelGrid>
</h:panelGrid>
<h:message for ="yesNoRadio"> </h:message>
<h:panelGrid id="userDetailsGrid">
<h:panelGrid columns="2" rendered="#{user.userDetailsGridFlag}">
<h:outputLabel>Name :</h:outputLabel>
<h:inputText id="customerName" value="#{user.customerName}"></h:inputText>
<h:outputLabel>Salary: </h:outputLabel>
<h:inputText id="customerSalary" value="#{user.customerSalary}"></h:inputText>
</h:panelGrid>
</h:panelGrid>
</h:form>
</h:body>
</html>
Model+Controller mingled:
package com.jsf.test;
import javax.faces.bean.*;
import javax.faces.event.ValueChangeEvent;
#ManagedBean
public class User {
private String userName;
private String password;
private String message;
private String customerName;
private String customerSalary;
private Integer yesNoRadio;
private Boolean yesNoRadioGridFlag;
private Boolean userDetailsGridFlag;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerSalary() {
return customerSalary;
}
public void setCustomerSalary(String customerSalary) {
this.customerSalary = customerSalary;
}
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 Integer getYesNoRadio() {
return yesNoRadio;
}
public void setYesNoRadio(Integer yesNoRadio) {
this.yesNoRadio = yesNoRadio;
}
public Boolean getUserDetailsGridFlag() {
return userDetailsGridFlag;
}
public void setUserDetailsGridFlag(Boolean userDetailsGridFlag) {
this.userDetailsGridFlag = userDetailsGridFlag;
}
public Boolean getYesNoRadioGridFlag() {
return yesNoRadioGridFlag;
}
public void setYesNoRadioGridFlag(Boolean yesNoRadioGridFlag) {
this.yesNoRadioGridFlag = yesNoRadioGridFlag;
}
public String validateLogin() {
if (userName.equals("xyz") && password.equals("xyz")) {
message = "Login Success";
yesNoRadioGridFlag = true;
} else {
yesNoRadioGridFlag = false;
message = "Login Failure";
}
return message;
}
public void loadYesNo(ValueChangeEvent evt){
Integer yesNoValue = (Integer)evt.getNewValue();
setYesNoRadio(yesNoValue);
userDetailsGridFlag = true;
}
}
You need to put the bean in the view scope in order to retain the underlying condition of the rendered attribute for the subsequent requests.
#ManagedBean
#ViewScoped
public class User {
// ...
}
Unrelated to the concrete problem, the valueChangeListener is intended to be used whenever you want to have a hook on the server side value change event which allows you to have both the old value and the new value at your hands. For example, to log an event. It's not intended to perform business actions based on the change. For that you should be using the listener attribute of <f:ajax> instead.
So, replace
<h:selectOneRadio id="yesNoRadio" value ="#{user.yesNoRadio}" valueChangeListener="#{user.loadYesNo}">
<f:selectItem itemValue="1" itemLabel="YES"></f:selectItem>
<f:selectItem itemValue="0" itemLabel="NO"></f:selectItem>
<f:ajax event="change" execute="#form" render="userDetailsGrid "></f:ajax>
</h:selectOneRadio>
with
<h:selectOneRadio id="yesNoRadio" value ="#{user.yesNoRadio}">
<f:selectItem itemValue="1" itemLabel="YES"></f:selectItem>
<f:selectItem itemValue="0" itemLabel="NO"></f:selectItem>
<f:ajax execute="#form" listener="#{user.loadYesNo}" render="userDetailsGrid"></f:ajax>
</h:selectOneRadio>
and remove the ValueChangeEvent attribute from the method.

Resources