Request parameter is null during postback - jsf-2

I have a view that display a list of users, from this view I can go to another view of "details" of any selected user. In the details view I need to select some values from 2 select list and then in the backed bean take these values, and add them to an user to finally store (update) the user in the database. These are my methods in the "user Bean".
With this method I get the user id from the "list of users view" and retrieve the user from the database to display its info on the details view.
public void getParam(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
With this method I set the values from the select list to an object and then I add this object to the user, finally I save it on the database.
public void setPrivilegio(){
System.out.println("hola");
Privilegio pri=new Privilegio();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map parameterMap = externalContext.getRequestParameterMap();
Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
System.out.println(agrupacion.getNombre());
Rol rol = (Rol)parameterMap.get("rols");
System.out.println(rol.getNombre());
System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
pri.setRol(rol);
pri.setAgrupacion(agrupacion);
pri.setActive(true);
this.getU().addPrivilegio(pri);
controlador.saveUsuario(this.getU());
}
This is my view:
<?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">
<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">
<div class="container">
<h:panelGroup id="Usuarios">
<h:form id="FormUsuarios">
<h2>Detalles Usuario</h2>
<h:dataTable id="users" value="#{usuario.u}" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{usuario.u.id}
</h:column>
<h:column>
<f:facet name="header">Identificador</f:facet>
<h:inputText id="identificador" value="#{usuario.u.identificador}" />
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
<h:inputText id="nombres" value=" #{usuario.u.nombres}"/> <h:inputText id="apellidoP" value=" #{usuario.u.apellidoPaterno}"/> <h:inputText id="apellidoM" value=" #{usuario.u.apellidoMaterno}"/>
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="check" value="#{usuario.u.active}"></h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
<h3>Asignar Privilegios</h3>
<h:selectOneMenu id="agrup" value="#{usuario.selected}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{agrupacion.agrupacion}" var="entity" itemLabel="#{entity.nombre}" itemValue="#{entity.id}"/>
</h:selectOneMenu>
<h:selectOneMenu id="rols" value="#{rol.selected}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{rol.roles}" var="rol" itemLabel="#{rol.nombre}" itemValue="#{rol.id}"/>
</h:selectOneMenu>
<h:commandButton value="Asignar" styleClass="btn-primary" actionListener="#{usuario.setPrivilegio}">
</h:commandButton>
<h3>Privilegios Asignados:</h3>
<h:dataTable id="privilegios" value="#{usuario.u.privilegios}" var="p" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{p.id}
</h:column>
<h:column>
<f:facet name="header">Roles</f:facet>
#{p.rol.nombre}
</h:column>
<h:column>
<f:facet name="header">Grupos</f:facet>
#{p.agrupacion.nombre}
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="checkbox" value="#{p.active}"></h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
</h:form>
<script type="text/javascript" src="js/paging-bootstrap.js"></script>
<script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
</h:panelGroup>
</div>
</ui:composition>
When I click on my commandbutton called "Asignar" that calls the method setPrivilegio(), I get this error:
java.lang.NumberFormatException: null
at java.lang.Long.parseLong(Long.java:404)
at java.lang.Long.valueOf(Long.java:540)
at cl.uchile.sti.bean.UsuarioBean.getParam(UsuarioBean.java:114)
The tables in the view shows all the info, but when I want to call the method that add the selected items to the user and save it on the database (setPrivilegio) I get this error.
How is this caused and how can I solve it?
This is my full "user bean":
#ManagedBean(name = "usuario")
#ViewScoped
public class UsuarioBean {
private usuarioController controlador;
private Usuario u=new Usuario();
private Privilegio Selected=new Privilegio();
private Boolean active;
private long id_user;
#PostConstruct
public void init() {
controlador=new usuarioController();
}
public long getId_user() {
return id_user;
}
public void setId_user(long id_user) {
this.id_user = id_user;
}
public Privilegio getSelected() {
return Selected;
}
public void setSelected(Privilegio selected) {
Selected = selected;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Usuario getU() {
getParam();
return u;
}
public void setU(Usuario u) {
this.u = u;
}
private List<Usuario> usuario;
public List<Usuario> getUsuario() {
usuario=UsuarioDAO.getAll();
return usuario;
}
public Usuario getById(long id_usuario){
return u;
}
public void setUsuario(List<Usuario> usuario) {
this.usuario = usuario;
}
public void saveUsuario(Usuario u){
controlador.saveUsuario(u);
}
public void getParam(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
public void setPrivilegio(){
System.out.println("hola");
Privilegio pri=new Privilegio();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map parameterMap = externalContext.getRequestParameterMap();
Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
System.out.println(agrupacion.getNombre());
Rol rol = (Rol)parameterMap.get("rols");
System.out.println(rol.getNombre());
System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
pri.setRol(rol);
pri.setAgrupacion(agrupacion);
pri.setActive(true);
this.getU().addPrivilegio(pri);
controlador.saveUsuario(this.getU());
}
}
this is the first view (list of users, from which i go to user details)
<?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">
<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">
<div class="container">
<h:panelGroup id="Usuarios">
<h:form id="FormUsuarios">
<h2>Listado de Usuarios</h2>
<h:graphicImage url="http://a.dryicons.com/images/icon_sets/simplistica/png/128x128/add.png" width="30" height="30"/>
<h:dataTable id="users" value="#{usuario.usuario}" var="o" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{o.id}
</h:column>
<h:column>
<f:facet name="header">Identificador</f:facet>
#{o.identificador}
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
#{o.nombres} #{o.apellidoMaterno} #{o.apellidoPaterno}
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="check" value="#{o.active}"></h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="header">Detalles</f:facet>
<h:outputLink value="contenido/detalleUsuario.xhtml">
Detalle
<f:param name="id_usuario" value="#{o.id}" />
</h:outputLink>
</h:column>
</h:dataTable>
</h:form>
<script type="text/javascript" src="js/paging-bootstrap.js"></script>
<script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
</h:panelGroup>
</div>
</ui:composition>

Bad getter!
public Usuario getU() {
getParam();
return u;
}
The getter above is a very bad idea. You've said it yourself that the variable makes it into the usuario backing bean(this I doubt). It is just plain wrong to perform business logic inside a getter because of inconsistencies (like you're experiencing) and the fact that the getter is called multiple times during a request. There are more elegant and cleaner ways to pass and initialise parameters between JSF pages.
private Usuario u=new Usuario(); is also a bad idea. Why is this necessary when you have
this.setU(controlador.getUser(param));
All that should happen inside your #PostConstructor
#PostConstruct
public void init() {
controlador=new usuarioController();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
The getter should just be plain
public Usuario getU() {
return u;
}

The cause of this error is that parameterMap.get("id_usuario") is null. You should investigate how you pass this parameter from the UI to the backing bean.

Related

Not getting value on selection of row using prime faces

i am having problem on getting the value on selection of row under the table field using prime faces.
Requirement is that as i select row the associated data and relevant information must be shown on same page here like i want to show only gender and address of particular user under the table .
I am using jsf 2.0 and prime faces 3.5
here is my code please check it where i have mistaking
package com.poc.faces;
all imports
.............
..............
#ManagedBean
#SessionScoped
public class UserManagedBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<User> list = new ArrayList<User>();
static {
list.add(new User(3, "ankurjadiya", "jadiyaankur#gmail.com",
"88849113", new Date(), "M", "sare ga ma pa"));
list.add(new User(1, "Administrator", "admin#gmail.com", "9000510456",
new Date(), "M", "Hyderabad"));
list.add(new User(2, "Guest", "guest#gmail.com", "9247469543",
new Date(), "M", "Hyderabad"));
list.add(new User(3, "John", "John#gmail.com", "9000510456",
new Date(), "M", "Hyderabad"));
list.add(new User(4, "Paul", "Paul#gmail.com", "9247469543",
new Date(), "M", "Hyderabad"));
list.add(new User(5, "raju", "raju#gmail.com", "9000510456",
new Date(), "M", "Hyderabad"));
}
private String username;
private String password;
private String searchUser;
private User selectedUser;
private UserDataModel dataModel;
public UserManagedBean() {
this.dataModel = new UserDataModel(list);
}
setter and getter of fields
..............
...............
public String login() {
if ("ankur".equalsIgnoreCase(getUsername())
&& "ankur".equals(getPassword())) {
return "home";
} else {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("username", new FacesMessage(
"Invalid UserName and Password"));
return "login";
}
}
User data model class
public class UserDataModel extends ListDataModel<User> implements Serializable,
SelectableDataModel<User> {
public UserDataModel() {
}
public UserDataModel(List<User> users) {
super(users);
}
public User getRowData(String username) {
List<User> list = (List<User>) getWrappedData();
for (User user : list) {
if (user.getUsername().equals(username))
return user;
}
return null;
}
public Object getRowKey(User user) {
// TODO Auto-generated method stub
return user.getUsername();
}
}
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("User Unselected",
((User) event.getObject()).getUsername());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
This is home.xtml where i retrieving the value
<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>
<h:form prependId="false" id="form">
<p:layout style="min-width:400px;min-height:200px;" id="layout"
fullPage="true">
<p:layoutUnit position="west" header="Menu" collapsible="true">
<p:menu>
<p:submenu label="Resources">
<p:menuitem value="Option1"
action="#{userManagedBean.getSearchUsersResults()}"
update="left_column" />
</p:submenu>
</p:menu>
</p:layoutUnit>
<p:layoutUnit position="center">
<p:panel id="left_column"
style="width: 2px; left: 2px; margin-left: 2px">
<center>
<H1>UserData</H1>
<br />
<p:dataTable value="#{userManagedBean.dataModel}" var="user"
pagination="true" rows="5" selection="#{userManagedBean.selectedUser}" selectionMode="single" >
<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>
</p:panel>
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Gender:" />
<h:inputText value="#{userManagedBean.selectedUser.gender}" />
<h:outputText value="Address:" />
<h:inputText value="#{userManagedBean.selectedUser.address}" />
</h:panelGrid>
` </p:layoutUnit>
<p:layoutUnit position="south" footer="bottom">
</p:layoutUnit>
</p:layout>
</h:form>
</h:body>
</html>
You need to set the rowKey attribute on the <p:dataTable/> to properly enable row selection. The rowKey attribute should be set to a unique identifier for the entity in your datatable, like the primary key attribute. From your sample, it'll look something like:
<p:dataTable value="#{userManagedBean.dataModel}" rowKey="#{user.userId}" var="user" pagination="true" rows="5" selection="#{userManagedBean.selectedUser}" selectionMode="single">

JSF #ViewScoped Bean State is Lost

I am using #ViewScoped Bean for small CRUD application I have a edit and view page but when I click buttons (edit) it will render edit form. After edit form appears the save button or cancel button does not call the function but renders the whole page. The actionListener's function is not called at all and everthing is initialized. Is something wrong with my bean and page?? I am using JSF 2 with richfaces and facelet.
//ViewScoped Bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.legendMgr.Legend;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
/**
*
* #author kitex
*/
#ManagedBean(name = "legendbean")
#ViewScoped
public class LegendController implements Serializable {
LegendDTO legendDTO;
String selectedLegend;
List<LegendDTO> legendDTOs;
boolean edit;
public List<LegendDTO> getLegendDTOs() {
return legendDTOs;
}
public void setLegendDTOs(List<LegendDTO> legendDTOs) {
this.legendDTOs = legendDTOs;
}
#PostConstruct
void initialiseSession() {
FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
public LegendController() {
if (!edit) {
legendDTO = new LegendDTO();
legendDTO.getList().add(new Legend());
legendDTOs = getLegends();
}
}
public String getSelectedLegend() {
return selectedLegend;
}
public void setSelectedLegend(String selectedLegend) {
this.selectedLegend = selectedLegend;
}
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public LegendDTO getLegendDTO() {
return legendDTO;
}
public void setLegendDTO(LegendDTO legendDTO) {
this.legendDTO = legendDTO;
}
public void addLegendRange() {
Logger.getLogger(LegendController.class.getName()).warning("List Size " + legendDTO.getList().size());
legendDTO.getList().add(new Legend());
Logger.getLogger(LegendController.class.getName()).warning("List Size " + legendDTO.getList().size());
}
public void removeLegendRange(Legend legend) {
if (legendDTO.getList().size() != 1) {
legendDTO.getList().remove(legend);
}
}
public String saveLegend() {
Logger.getLogger(LegendController.class.getName()).warning("Save Legend Edit" + edit);
LegendDAO dao = new LegendDAO();
if (dao.addLegend(legendDTO, edit)) {
edit = false;
Logger.getLogger(LegendController.class.getName()).warning("Save Legend Edit" + edit);
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Could Not Save Confim if you have already defined Legend " + legendDTO.getLegendName() + "!"));
}
return "";
}
public String cancel() {
edit = false;
legendDTO = new LegendDTO();
legendDTO.getList().add(new Legend());
return "";
}
public List<LegendDTO> getLegends() {
LegendDAO dao = new LegendDAO();
return dao.getLegendDTO();
}
//All function from here are for legend delete
public void deleteLegendType(LegendDTO dto) {
LegendDAO dao = new LegendDAO();
if (dao.deleteLegendType(dto.getLegendName())) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Deleted !"));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Deleted Error !"));
}
}
//All function from here is to legend edit
public void editLegendType(LegendDTO dto) {
edit = true;
Logger.getLogger(LegendController.class.getName()).warning("DTO : " + dto.legendName);
legendDTO = dto;
LegendDAO dao = new LegendDAO();
Logger.getLogger(LegendController.class.getName()).warning("Edit dto set");
try {
List<Legend> legends = dao.getDetailForEditLegend(dto.getLegendName());
if (legends == null || legends.isEmpty()) {
dto.getList().add(new Legend());
} else {
dto.setList(legends);
}
} catch (SQLException ex) {
Logger.getLogger(LegendController.class.getName()).warning("SQL EXception has occoured");
}
Logger.getLogger(LegendController.class.getName()).warning("In Edit Legend Function The size of list" + dto.getList().size());
}
}
//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 xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<ui:composition template="/legendTemplate.xhtml">
<ui:define name="windowTitle">Change Legend</ui:define>
<ui:define name="content">
<h:messages globalOnly="true"/>
<rich:panel id="firstPanel">
<h:form id="nis_viewLegend">
<rich:dataTable id="data_tbl" value="#{legendbean.legendDTOs}" var="legendDTOvar" style="width:100%" rendered="#{!legendbean.edit and not empty legendbean.legendDTOs}">
<rich:column>
<f:facet name="header">
<h:outputText value="Description"/>
</f:facet>
<h:outputText value="#{legendDTOvar.desc}"/>
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="Legend Type"/>
</f:facet>
<h:outputText value="#{legendDTOvar.legendName}"/>
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="Legend Type"/>
</f:facet>
<h:outputText value="#{legendDTOvar.legendFor}"/>
</rich:column>
<rich:column>
<a4j:commandLink value="Delete" actionListener="#{legendbean.deleteLegendType(legendDTOvar)}" render=":firstPanel"/>
<h:outputText value="/"/>
<a4j:commandLink value="Edit" actionListener="#{legendbean.editLegendType(legendDTOvar)}" render=":secondPanel :editLegendForm :nis_viewLegend"/>
</rich:column>
</rich:dataTable>
</h:form>
</rich:panel>
<rich:panel id="secondPanel">
<h:form id="editLegendForm" rendered="#{legendbean.edit}">
<h:outputText value="Legend Name"/><br/>
<h:inputText value="#{legendbean.legendDTO.legendName}" readonly="true"/><br/>
<h:outputText value="Description"/><br/>
<h:inputText value="#{legendbean.legendDTO.desc}"/><br/>
<h:outputText value="Legend For"/><br/>
<h:inputText value="#{legendbean.legendDTO.legendFor}"/><br/>
<br/>
<h:outputText value="Range" />
<rich:dataTable id="editDataPnl" value="#{legendbean.legendDTO.list}" var="legend" style="width:100%">
<rich:column>
<f:facet name="header">
<h:outputText value="SN"/>
</f:facet>
<h:inputText value="#{legend.sn}"/>
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="Description"/>
</f:facet>
<h:inputText value="#{legend.desc}"/>
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="Lower Range"/>
</f:facet>
<h:inputText value="#{legend.lowerRange}"/>
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="Upper Range"/>
</f:facet>
<h:inputText value="#{legend.upperRange}"/>
</rich:column>
<rich:column>
<f:facet name="header">
<h:outputText value="Color"/>
</f:facet>
<h:inputText value="#{legend.color}"/>
</rich:column>
<rich:column>
<a4j:commandLink value="Add" actionListener="#{legendbean.addLegendRange}" render=":secondPanel"/>
<h:outputText value=" / "/>
<a4j:commandLink value="Remove" actionListener="#{legendbean.removeLegendRange(legend)}" render=":secondPanel"/>
</rich:column>
</rich:dataTable>
<br/>
<center>
<a4j:commandButton value="SAVE" action="#{legendbean.saveLegend()}" render=":firstPanel :secondPanel"/>
<a4j:commandButton value="CANCEL" action="#{legendbean.cancel()}" render=":firstPanel :secondPanel"/>
</center>
</h:form>
</rich:panel>
</ui:define>
</ui:composition>
</h:body>
</html>
In ViewScope, once the view is built, for example form.xhtml, its data will last as long you do not go away from this view. To stay in the same view you should call methods that has return type void (which are usually used in actionListener property) or return null, in case of returning an outcome for navigation.
Method expression
In your case your methods are void but instead of passing it to the action listener you're calling it in the view.
Try changing similar code like this:
<a4j:commandButton value="SAVE" actionListener="#{legendbean.saveLegend()}" render="mainPnl"/>
To this:
<a4j:commandButton value="SAVE" actionListener="#{legendbean.saveLegend}" render="mainPnl"/>
As actionListener property already expects a method expression.
Form inside dataTable
Also I noticed you have a form inside your dataTable. That could lead to strange behavior because your form has an id it will be repeated in the resulting page. For that you should try placing the form outside the dataTable.
Even better you could have only one form enclosing the entire code as nested forms are invalid HTML code.
I would suggest you check your legendTemplate.xhtml against nested forms too.
Bean construction
In order to initialize your bean state it is recommended to use a #PostContruct method instead of the bean constructor.
Try changing from this:
public LegendController() {
legendDTO = new LegendDTO();
legendDTO.getList().add(new Legend());
}
To this:
#PostConstruct
public void reset() {
legendDTO = new LegendDTO();
legendDTO.getList().add(new Legend());
}
And delete your constructor.
Your bean data should be kept as long as you're in the same view (aka .xhtml page).
I hope it helps.
I am having the same problem. I don't think the answers above really address the question. He is not having a problem as a result of submitting any forms - pressing those buttons themselves results in the whole page re-rendering, which means that the reference to the view state is already gone before the button is pressed. This is what I am observing as well. For me, it only happens when there are a lot of large search results, and simply re-submitting the same search I just did re-renders the page (without executing the search). I believe the problem has to do with a limit on the amount of data that can be passed to the server in a form: in view scope, all of the data is serialized and passed around in one long hidden value as a value in the form. If that value is too long the server won't accept it and, therefore, will not remember the previous state.
I know this is not definitive, but this is only thread out there on this problem I can find so I hope it helps shed light for others or inspires better information. If you have something more definitive please let us know.
Edit: I am convinced now that this was the problem. My model bean had a reference to a file blob. Once I replaced that reference with a boolean (only needed to know if it existed) the problem went away. Try passing around references to your DTOs/DAOs instead of the objects themselves, or mark them as "transient" where you don't need them to persist. Or, if possible, lighten the objects as I did.
Did you try to return null for functions saveLegend() and cancel() instead of returning empty string?
public String saveLegend() {
---------
return null;
}
public String cancel() {
----------
return null;
}
Return can also be void for ajax request. But if I remember it correctly for richfaces returning null is the only solution. Give it a try. :)
The cancel() works as it reinitialize the bean.
As answered by Bento you cannot pass values using actionListener. Use action instead.
Further Reading:
JSF 2 ViewScope questions
JSF2 Action parameter
Differences between action and actionListener

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 :)

Primefaces ajax row selection fail to update values in dialog

I have a data table that will display a detail dialog on row select event. However, the dialog does not show any values of the selected object. I can see that the selected object is properly set during debug session.
The table consists of rows of students and it is suppose to display a popup dialog showing detailed information on row selection event.
The StudentBean:
#Named(value = "studentBean")
#SessionScoped
public class StudentBean {
#Inject
private UserFacade userFacade;
private List<User> studentList;
private User selectedStudent;
public StudentBean() {
}
#PostConstruct
public void init() {
studentList = userFacade.findAll();
}
public List<User> getStudentList() {
return studentList;
}
public void setStudentList(List<User> studentList) {
this.studentList = studentList;
}
public User getSelectedStudent() {
return selectedStudent;
}
public void setSelectedStudent(User student) {
this.selectedStudent = student;
}
public void onRowSelect(SelectEvent event) {
}
public void onRowUnselect(UnselectEvent event) {
//FacesMessage msg = new FacesMessage("Student Unselected", ((User) event.getObject()).getFirstName());
//FacesContext.getCurrentInstance().addMessage("messages", msg);
}
}
The Facelet page:
<?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:p ="http://primefaces.org/ui">
<body>
<ui:composition template="./layout.xhtml">
<ui:define name="content">
<h:form id="studentForm">
<p:dataTable var="student" value="#{studentBean.studentList}"
selectionMode="single"
selection="#{studentBean.selectedStudent}" rowKey="#{student.id}">
<p:ajax event="rowSelect" listener="#{studentBean.onRowSelect}"
update=":studentForm:studentDetail" oncomplete="studentDialog.show()"
global="true" immediate="true"
/>
<p:ajax event="rowUnselect" listener="#{studentBean.onRowUnselect}" />
<p:column headerText="First Name">
<h:outputText value="#{student.firstName}" />
</p:column>
<p:column headerText="Last Name">
<h:outputText value="#{student.lastName}" />
</p:column>
<p:column headerText="Student ID">
<h:outputText value="#{student.studentid}" />
</p:column>
</p:dataTable>
<p:dialog id="dialog" header="Student Detail" widgetVar="studentDialog" resizable="false"
showEffect="fade" hideEffect="fade" appendToBody="true">
<h:panelGrid id="studentDetail" columns="2" cellpadding="4">
<h:outputText value="First Name: " />
<h:outputText value="#{studentBean.selectedStudent.firstName}" />
<h:outputText value="Last Name: " />
<h:outputText value="#{studentBean.selectedStudent.lastName}" />
</h:panelGrid>
</p:dialog>
</ui:define>
</ui:composition>
</body>
</html>
I'm following the Car data table example from the Primefaces Showcase page. It seems so simple there but I can't seem to display the selectedStudent information no matter what I do. The dialog shows up fine but the firstName and lastName values are empty.
I tried the following:
Putting the dialog into another form
Use process="#form"
Use process=":studentForm:studentDetail"
What am I doing wrong?
Primefaces 3.3.1,
Glassfish 3.1.2
I removed global="true" immediate="true", unused listeners
from p:ajax, synchronized rowKey="#{student.id}"
with expression from "Student ID" column and populated
studentList inside #PostConstruct init() function not knowing how yours userFacade code is, and it works.

How to do CRUD operation with PrimeFaces datatable

I have one datatable created with a PrimeFaces 3.3 datatable. This table is populated from a database.
On a row selection, I populate similar fields for editing. Once edited, I want to write to the db. Similarly, I want to be able to create a new record in text items and once the user saves it the datatable to be refreshed.
Data selection works fine, however, when I cant figure out way for add/edit/delete, different errors come with different approach and I have tried all methods I could find on Google. These errors are some time logical errors and some times nullpointerexception or class initiation errors. I have tried over a dozen examples available on net for jtable + crud but seems nothing works fine for me.
For example, data is displayed in data table and instant selection in the text fields is also done but when i click add button, nothing happens, I expect fields in 'edit properties' panel to be cleared, sometimes I get a NullPointerException, even if I modify values in text items and press save, values are not written. When I debugged, I found error coming in em.getTransaction().begin line.
If I use em.joinTransaction it again throws an error on the commit statement. Since I am new to Java EE I think I am making some terrible mistakes.
I will appreciate if some one can give some example of a similar scenario: jtable + bound fields + add / edit / delete operations.
below is my code:
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findByIduser", query = "SELECT u FROM Users u WHERE u.iduser = :iduser"),
#NamedQuery(name = "Users.findByLogin_Name", query = "SELECT u FROM Users u WHERE u.login_name = :login_name"),
#NamedQuery(name = "Users.findByFullName", query = "SELECT u FROM Users u WHERE u.fullName = :fullName"),
#NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password"),
#NamedQuery(name = "Users.authenticate", query = "SELECT u FROM Users u WHERE u.login_name = :login_name and u.password = :password and u.active=1"),
#NamedQuery(name = "Users.findByActive", query = "SELECT u FROM Users u WHERE u.active = :active"),
#NamedQuery(name = "Users.findByUserType", query = "SELECT u FROM Users u WHERE u.userType = :userType"),
#NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email"),
#NamedQuery(name = "Users.findByPhone", query = "SELECT u FROM Users u WHERE u.phone = :phone"),
#NamedQuery(name = "Users.findByCreated", query = "SELECT u FROM Users u WHERE u.created = :created"),
#NamedQuery(name = "Users.findByUpdated", query = "SELECT u FROM Users u WHERE u.updated = :updated")})
public class Users implements Serializable {
#Basic(optional = false)
#NotNull
#Column(name = "created")
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#Basic(optional = false)
#NotNull
#Column(name = "updated")
#Temporal(TemporalType.TIMESTAMP)
private Date updated;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
#Basic(optional = false)
#NotNull
#Column(name = "iduser")
private Integer iduser;
//getter & setters ....
#Stateless
public class UsersFacade extends AbstractFacade<Users> {
#PersistenceContext(unitName = "VUProjectPU")
private EntityManager em;
///////////////////////////////////////////////////////////////////////////////
#Override
protected EntityManager getEntityManager() {
return em;
}
///////////////////////////////////////////////////////////////////////////////
public UsersFacade() {
super(Users.class);
}
///////////////////////////////////////////////////////////////////////////////
public Users authenticate(String login_id, String pwd) {
List <Users> userList = new ArrayList();
Users user =null;
userList = em.createNamedQuery("Users.authenticate")
.setParameter("login_name", login_id)
.setParameter("password", pwd)
.getResultList();
if (userList.isEmpty()) {
return null;
}
else{
user = userList.get(0);
}
return user;
}
///////////////////////////////////////////////////////////////////////////////
public Users deactivateUser (Users u){
u.setActive(false);
return u;
}
///////////////////////////////////////////////////////////////////////////////
public Users activateUser (Users u){
u.setActive(true);
return u;
}
///////////////////////////////////////////////////////////////////////////////
public Users createAnalyst(Users u){
u.setActive(false);
u.setUserType("Analyst");
u.setCreated(new Date());
u.setUpdated(new Date());
em.persist(u);
em.flush();
em.refresh(u);
return u;
}
}
#ManagedBean
#ViewScoped
public class UsersList implements Serializable {
private List<Users> uList;
private Users selUser ;
private Users user;
private String operation;
private #EJB UsersFacade ufs;
private FacesContext context;
private FacesMessage msg;
private Boolean edit=false;
public UsersList(){
ufs = new UsersFacade();
}
public void getAllUsersList(){
uList=ufs.findAll();
}
public Boolean isEdit() {
return edit;
}
public void add(){
context = FacesContext.getCurrentInstance();
operation = "new";
edit=true;
selUser = new Users();
}
public void save(){
context = FacesContext.getCurrentInstance();
if (operation.equals("new")){
ufs.create(selUser);
}
ufs.save(selUser);
operation = null;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Success", "Record Saved");
context.addMessage(null, msg);
edit=false;
getAllUsersList(); //refresh table
}
public void delete(Users u){
context = FacesContext.getCurrentInstance();
ufs.delete(u);
msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Success", "Record Deleted");
context.addMessage(null, msg);
}
public void refresh(){
context = FacesContext.getCurrentInstance();
getAllUsersList();
msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Success", "Data Refreshed");
context.addMessage(null, msg);
}
public List<Users> getuList() {
uList = ufs.findAll();
return uList;
}
public void setuList(List<Users> uList) {
this.uList = uList;
}
public Users getSelUser() {
return selUser;
}
public void setSelUser(Users selUser) {
this.selUser = selUser;
}
public void onRowSelect(SelectEvent event) {
edit=true;
context = FacesContext.getCurrentInstance();
msg = new FacesMessage("User Selected", ((Users) event.getObject()).getLogin_name());
context.addMessage(null, msg);
}
public void onRowUnSelect(UnselectEvent event) {
edit=false;
context = FacesContext.getCurrentInstance();
msg = new FacesMessage("User Unselected", ((Users) event.getObject()).getLogin_name());
context.addMessage(null, msg);
}
public Users getUser() {
return user;
}
}
below is user.xhtml
<?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:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<body>
<ui:composition template="./../../WEB-INF/Templates/Template.xhtml">
<ui:define name="menu">
</ui:define>
<ui:define name="content">
<h:form id="form">
<p:growl id="growl" showDetail="true"/>
<p:dataTable id="utable" var="users"
value="#{usersList.getuList()}"
selection="#{usersList.selUser}"
rowKey="#{users.iduser}"
selectionMode="single"
paginator="true" rows="5"
paginatorPosition="bottom"
editable="true"
>
<p:ajax event="rowSelect" listener="#{usersList.onRowSelect}" update=":form:display :form:growl" />
<p:ajax event="rowUnselect" listener="#{usersList.onRowUnSelect}" update=":form:growl"/>
<f:facet name="header">
List of Users
</f:facet>
<p:column id="login" sortBy ="#{users.login_name}">
<f:facet name="header">Login</f:facet>
<h:outputText value="#{users.login_name}" />
</p:column>
<p:column id="fullname" sortBy ="#{users.fullName}">
<f:facet name="header">User Name</f:facet>
<h:outputText value="#{users.fullName}" />
</p:column>
<p:column id="email" sortBy ="#{users.email}">
<f:facet name="header">E-mail</f:facet>
<h:outputText value="#{users.email}" />
</p:column>
<p:column id="phone" sortBy ="#{users.phone}">
<f:facet name="header">Phone</f:facet>
<h:outputText value="#{users.phone}" />
</p:column>
<p:column id="created" sortBy ="#{users.created}">
<f:facet name="header">Created On</f:facet>
<h:outputText value="#{users.created}" />
</p:column>
<p:column id="active" sortBy ="#{users.active}">
<f:facet name="header">Active</f:facet>
<h:outputText value="#{users.active}" />
</p:column>
<p:column id="userType" sortBy ="#{users.userType}">
<f:facet name="header">User Type</f:facet>
<h:outputText value="#{users.userType}" />
</p:column >
</p:dataTable>
<p:panel header="Edit User Properties">
<h:panelGrid id="display" columns="6" cellpadding="4" >
<h:outputText value="Login:" />
<p:inputText readonly="#{usersList.edit}"
value="#{usersList[usersList.edit ? 'user' : 'selUser'].login_name}" />
<h:outputText value="Password:" />
<p:inputText readonly="#{usersList.edit}"
value="#{usersList[usersList.edit ? 'user' : 'selUser'].password}" />
<h:outputText value="User Name:" />
<p:inputText readonly="#{usersList.edit}"
value="#{usersList[usersList.edit ? 'user' : 'selUser'].fullName}" />
<h:outputText value="E-mail:" />
<p:inputText readonly="#{usersList.edit}"
value="#{usersList[usersList.edit ? 'user' : 'selUser'].email}" />
<h:outputText value="Phone:" />
<p:inputText readonly="#{usersList.edit}"
value="#{usersList[usersList.edit ? 'user' : 'selUser'].phone}" />
<h:outputText value="User Type:" />
<p:inputText readonly="#{usersList.edit}"
value="#{usersList[usersList.edit ? 'user' : 'selUser'].userType}" />
<h:outputText value="Active:" />
<p:selectBooleanCheckbox
value="#{usersList[usersList.edit ? 'user' : 'selUser'].active}"/>
</h:panelGrid>
<h:panelGrid id="command" columns="6" cellpadding="4" >
<p:commandButton id="new" value="New" actionListener="#{usersList.add()}"
update="result,utable,display"
rendered="#{usersList.edit}}">
</p:commandButton>
<p:commandButton id="save" value="Save" actionListener="#{usersList.save()}" update="result utable">
</p:commandButton>
<p:commandButton id="delete" value="Delete" actionListener="#{usersList.delete()}" update="result utable">
</p:commandButton>
<p:commandButton id="refresh" value="Refresh" actionListener="#{usersList.refresh()}" update="result utable">
</p:commandButton>
</h:panelGrid>
<p:messages id="result" showDetail="true" autoUpdate="true"/>
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>

Resources