Primefaces datatable, not updated after delete a row - primefaces

I'm trying deleting a row from my primefaces datatable but it never updates itself until I refresh the browser.
This is how I'm doing it:
<p:column headerText="Eliminar Usuario" rendered="#{user.current.tipo.equalsIgnoreCase('planta')}">
<p:commandButton action="#{usuarios.eliminar(o.idUsuario)}" value="Eliminar" update="#form"/>
</p:column>
I've tried wrapping the datatable into an h:panelgroup, I also tried using update=":formUsuarios:users" (the id of my form is formUsuarios and the id of the table is users). I put "ajax="true" in the commandButton, nothing has worked.
I don't know what else to try. I'm using primefaces 3.5.
Here is my bean:
#ManagedBean(name = "usuarios")
#ViewScoped
public class UsuariosBean {
#ManagedProperty(value="#{user}")
private LoginBean loginBean;
private List<UsuariosEntity> usuarios;
UsuariosEntity user=new UsuariosEntity();
private String nombre;
private int activo;
private String tipo;
private String password;
private String selection;
private UIComponent mybutton;
#PostConstruct
public void init(){
UsuariosEntity usuario=loginBean.getCurrent();
usuarios=new ArrayList<UsuariosEntity>();
if(usuario.getTipo().equalsIgnoreCase("Planta")){
usuarios= UsuariosDAO.getALL();
}else{
usuarios= UsuariosDAO.getALLbyRol(usuario.getUsuario());
}
}
public UIComponent getMybutton() {
return mybutton;
}
public void setMybutton(UIComponent mybutton) {
this.mybutton = mybutton;
}
public String getSelection() {
return selection;
}
public void setSelection(String selection) {
this.selection = selection;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getActivo() {
return activo;
}
public void setActivo(int activo) {
this.activo = activo;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public LoginBean getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
public UsuariosEntity getUser() {
return user;
}
public void setUser(UsuariosEntity user) {
this.user = user;
}
public List<UsuariosEntity> getUsuarios() {
return usuarios;
}
public void setUsuarios(List<UsuariosEntity> usuarios) {
this.usuarios = usuarios;
}
public void newUsuario(){
UsuariosEntity user=new UsuariosEntity();
user.setIdPlanta(2);
user.setActivo(this.activo);
user.setPassword(this.password);
user.setUsuario(this.nombre);
user.setTipo(this.selection);
List<UsuariosEntity>usuariox=UsuariosDAO.findbyname(this.nombre);
if (usuariox.size()==0){
UsuariosDAO.save(user);
}else{
FacesMessage message = new FacesMessage("El usuario ya existe en la base de datos");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(mybutton.getClientId(context), message);
}
}
public void eliminar(int id_user){
UsuariosEntity user=UsuariosDAO.find(id_user);
UsuariosDAO.eliminar(user);
}
public void onEdit(RowEditEvent event) {
UsuariosDAO.save(((UsuariosEntity)event.getObject()));
FacesMessage msg = new FacesMessage("Usuario Editado", ((UsuariosEntity) event.getObject()).getUsuario());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edición Cancelada", ((UsuariosEntity) event.getObject()).getUsuario());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
the 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"
template="/Contenido/Template.xhtml"
xmlns:p="http://primefaces.org/ui">
<ui:define name="page-content">
<h:form id="formUsuarios">
<p:growl id="messages" showDetail="true"/>
<p:dataTable id="users" value="#{usuarios.usuarios}" var="o" editable="true" scrollRows="20" scrollable="true" scrollHeight="150" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<f:facet name="header">Usuarios</f:facet>
<p:ajax event="rowEdit" listener="#{usuarios.onEdit}" update=":formUsuarios:messages" />
<p:ajax event="rowEditCancel" listener="#{usuarios.onCancel}" update=":formUsuarios:messages" />
<p:column headerText="#" style="width:6%">
<h:outputText value=" #{o.idUsuario} "/>
</p:column>
<p:column rendered="#{user.current.tipo.equalsIgnoreCase('planta')}" headerText="Nombre">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.usuario}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.usuario}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Nombre" rendered="#{user.current.tipo.equalsIgnoreCase('productor')||user.current.tipo.equalsIgnoreCase('exportadora')}">
<h:outputText value="#{o.usuario}" />
</p:column>
<p:column rendered="#{user.current.tipo.equalsIgnoreCase('planta')}" headerText="Estado" style="width:6%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.activo}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.activo}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Password">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="********" />
</f:facet>
<f:facet name="input">
<h:inputSecret value="#{o.password}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column rendered="#{user.current.tipo.equalsIgnoreCase('planta')}" headerText="Tipo">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.tipo}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.tipo}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Editar" style="width:6%">
<p:rowEditor />
</p:column>
<p:column headerText="Eliminar Usuario" rendered="#{user.current.tipo.equalsIgnoreCase('planta')}">
<p:commandButton actionListener="#{usuarios.eliminar(o.idUsuario)}" value="Eliminar" process="users" ajax="true"/>
</p:column>
</p:dataTable>
<br/>
</h:form>
<h:form>
<p:panelGrid id="grid" columns="3" rendered="#{user.current.tipo.equalsIgnoreCase('planta')}">
<f:facet name="header">
Crear Usuario
</f:facet>
<h:outputText value="Nombre"/>
<h:inputText id="nombre" label="name" value="#{usuarios.nombre}" required="true" requiredMessage="Debe ingresar un nombre"/>
<h:message for="nombre" style="color:red"/>
<h:outputText value="Contraseña" />
<h:inputText id="pass" label="pasw" value="#{usuarios.password}" required="true" requiredMessage="Debe ingresar una contraseña"/>
<h:message style="color:red" for="pass"/>
<h:outputText value="Tipo"/>
<h:selectOneMenu id="select1" value="#{usuarios.selection}" onchange="submit();" required="true" requiredMessage="Debe seleccionar un tipo de usuario">
<f:selectItem itemValue="Planta" itemLabel="Planta" />
<f:selectItem itemValue="Exportadora" itemLabel="Exportadora" />
<f:selectItem itemValue="Productor" itemLabel="Productor" />
</h:selectOneMenu>
<h:message style="color:red" for="select1"/>
<h:outputText value="Activo"/>
<h:selectOneMenu id="select2" value="#{usuarios.activo}" onchange="submit();" required="true" requiredMessage="Debe seleccionar una opción ">
<f:selectItem itemValue="0" itemLabel="Inactivo" />
<f:selectItem itemValue="1" itemLabel="Activo" />
</h:selectOneMenu>
<h:message style="color:red" for="select2" />
<f:facet name="footer">
<h:commandButton value="Crear" id="mybutton"
binding="#{usuarios.mybutton}"
class="button" action="#{usuarios.newUsuario}">
</h:commandButton>
<h:message style="color:red" for="mybutton" />
</f:facet>
</p:panelGrid>
</h:form>
</ui:define>
</ui:composition>

Changing the collection referred by the value doesn't immediately affect data table because the values that are shown are stored by the filtered collection.
1) If you specify the filteredValue attribute, you should manually clear that collection after the data table content has changed, for example after deleting the row. After update on the data table, it should refresh the content.
2) You can call filter() on the dataTable widget (client-side API). It always works but it generates additional AJAX request.

Related

compositeComponent with primefaces datatable selection does not return object

I've made a composite component using primefaces 5.1. I want a dialog to show up, you can input a name and search the db. Then you can select one entry and the dialog closes again. My Problem ist that the selection in the dataTable always returns null...
this is the composite:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j" xmlns:p="http://primefaces.org/ui"
xmlns:composite="http://java.sun.com/jsf/composite">
<composite:interface componentType="searchCustomer">
<composite:attribute name="customerCache" required="true"
type="com.hji.tis.ui.cache.customer.CustomerCache" />
<composite:attribute name="useExtendedCustomersOnly" default="false" />
</composite:interface>
<composite:implementation>
<p:commandLink styleClass="ui-icon ui-icon-search"
id="searchCustomerIcon" onclick="PF('searchCustomerDialog').show();" />
<p:tooltip for="searchCustomerIcon"
value="#{msgs['request.searchByCustomerNumber']}" />
<p:dialog header="#{msgs['general.searchCustomer']}" resizable="false"
draggable="false" width="500" height="450" modal="true"
appendTo="#(body)" widgetVar="searchCustomerDialog">
<p:panel id="searchCustomerDialogContent" style="width:100%">
<p:panelGrid style="width:480px">
<p:row>
<p:column style="width:60px">
<p:graphicImage value="/resources/images/userSearch.png"
width="50" height="50" />
</p:column>
<p:column style="width:100px">
<p:outputLabel value="#{msgs['general.customerName']}" />
</p:column>
<p:column style="width:160px">
<p:inputText value="#{cc.custSearch_name}"
id="input_searchCustomerName" />
</p:column>
<p:column>
<p:commandLink styleClass="ui-icon ui-icon-search"
action="#{cc.findCustomersByName}"
update="searchCustomerDialogContent"
process="#this, input_searchCustomerName" partialSubmit="true" />
</p:column>
</p:row>
<p:row>
<p:column colspan="4">
<p:dataTable value="#{cc.filteredCustomers}" var="customer"
scrollable="true" scrollHeight="300"
emptyMessage="#{msgs['general.noSelection']}"
selection="#{cc.selectedCustomer}" rowKey="#{customer.id}"
selectionMode="single">
<p:ajax event="rowSelect" process="#this" />
<p:column headerText="#{msgs['general.customerName']}"
styleClass="unmarkable">
<h:outputText value="#{customer.fullName}"
rendered="#{!customer.extendedCustomer}" />
<h:outputText value="#{customer.name}"
rendered="#{customer.extendedCustomer}" />
</p:column>
<p:column headerText="#{msgs['general.address']}"
styleClass="unmarkable">
<h:outputText
value="#{customer.homeAddress.address.country}, #{customer.homeAddress.address.zipCode} #{customer.homeAddress.address.city}, #{customer.homeAddress.address.street} #{customer.homeAddress.address.houseNr}" />
</p:column>
</p:dataTable>
</p:column>
</p:row>
<p:row>
<p:column colspan="4">
<p:commandButton icon="ui-icon-check" style="float:right"
action="#{cc.test}" process="#this, searchCustomerDialogContent"
partialSubmit="true" />
</p:column>
</p:row>
</p:panelGrid>
</p:panel>
</p:dialog>
</composite:implementation>
</html>
and this is the Faces Component:
package com.hji.tis.ui.util.customComponents;
import java.io.IOException;
import java.util.List;
import javax.faces.component.FacesComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.event.SelectEvent;
import com.hji.tis.domain.model.customer.Customer;
import com.hji.tis.ui.cache.customer.CustomerCache;
/**
* NamingContainer for the custom element searchCustomer.
*
* #author mayra
*
*/
#FacesComponent("searchCustomer")
public class SearchCustomer extends UINamingContainer {
private final String CUSTOMER_CACHE = "customerCache";
private final String USER_EXTENDED_CUSTOMERS_ONLY = "useExtendedCustomersOnly";
private final String FILTERED_CUSTOMERS = "filteredCustomers";
private final String SELECTED_CUSTOMER = "selectedCustomer";
#Getter
#Setter
private String custSearch_name;
#Getter
#Setter
private Customer custSearch_selectedCustomer;
#Override
public void encodeBegin(FacesContext facesContext) throws IOException {
initCustomerCache();
initUseExtendedCustomersOnly();
super.encodeBegin(facesContext);
}
public void onRowSelect(SelectEvent event) {
System.out.println(((Customer) (event.getObject())).getFullName());
}
/**
* finds the customer by the name set to the _Name field. Decides wether
* only private Customers should be returned or extended.
*/
public void findCustomersByName() {
this.custSearch_selectedCustomer = null;
if (useExtendedCustomersOnly()) {
setFilteredCustomers(getCustomerCache().findExtendedCustomerEntriesByName(custSearch_name));
} else {
setFilteredCustomers(getCustomerCache().findAllCustomerEntriesByName(custSearch_name));
}
}
private boolean useExtendedCustomersOnly() {
return getStateHelperValue(USER_EXTENDED_CUSTOMERS_ONLY);
}
private CustomerCache getCustomerCache() {
return getStateHelperValue(CUSTOMER_CACHE);
}
public Customer getSelectedCustomer() {
return (Customer) this.getStateHelper().get(SELECTED_CUSTOMER);
}
public void setSelectedCustomer(Customer customer) {
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!HERE THE CUSTOMER IS ALWAYS NULL
this.getStateHelper().put(SELECTED_CUSTOMER, customer);
}
public List<Customer> getFilteredCustomers() {
return (List<Customer>) this.getStateHelper().get(FILTERED_CUSTOMERS);
}
private void setFilteredCustomers(List<Customer> customers) {
this.getStateHelper().put(FILTERED_CUSTOMERS, customers);
}
/**
* stores the customerCache in the state helper.
*/
private void initCustomerCache() {
CustomerCache customerCache = getAttributeValue(CUSTOMER_CACHE);
this.getStateHelper().put(CUSTOMER_CACHE, customerCache);
}
private void initUseExtendedCustomersOnly() {
String value = getAttributeValue(USER_EXTENDED_CUSTOMERS_ONLY);
boolean boolValue = false;
if (value.equalsIgnoreCase("TRUE")) {
boolValue = true;
} else {
boolValue = false;
}
this.getStateHelper().put(USER_EXTENDED_CUSTOMERS_ONLY, boolValue);
}
/**
* Return specified attribute value or otherwise the specified default if
* it's null.
*/
#SuppressWarnings("unchecked")
private <T> T getAttributeValue(String key) {
return (T) this.getAttributes().get(key);
}
#SuppressWarnings("unchecked")
private <T> T getStateHelperValue(String key) {
return (T) this.getStateHelper().get(key);
}
}
Maybe someone knows the reason why?
Thanks!

Send data primefaces to another page

I´m newbie in primefaces, i have done a datatable and i show it in index.xhtml i have got a button when i push, it show the selection datatable (dialog) but i don´t know how to send the select datatable to another page. Sorry I´m learning english, thx.
index.xhtml
<p:dataTable id="singleDT" var="emp" value="#{empresaBean.getEmpresaList()}" selectionMode="single"
scrollable="true" scrollHeight="400" selection="#{empresaBean.selectedEmpresa}" rowKey="#{emp.CLAVE}">
<f:facet name="header">
Lista de Empresas
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{emp.CLAVE}" />
</p:column>
<p:column headerText="Nombre Empresa">
<h:outputText value="#{emp.NOMBRE}" />
</p:column>
<p:column headerText="AÑO">
<h:outputText value="#{emp.EJERCICIO}" />
</p:column>
<f:facet name="footer">
<p:button outcome="/pages/menu/menuPrincipal.xhtml" value="Seleccionar" title="Ir Menu">
</p:button>
<p:commandButton value="View" image="ui-icon ui-icon-search"
oncomplete="empresaDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="empresaDialog" resizable="false"
width="200" showEffect="clip" hideEffect="fold">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Clave:" />
<h:outputText value="#{empresaBean.selectedEmpresa.CLAVE}" />
<h:outputText value="Año:" />
<h:outputText value="#{empresaBean.selectedEmpresa.NOMBRE}" />
<h:outputText value="Año:" />
<h:outputText value="#{empresaBean.selectedEmpresa.EJERCICIO}" />
</h:panelGrid>
</p:dialog>
</h:form>
</h:body>
EmpresaBean
#ManagedBean(name="empresaBean")
#Scope
#Component
public class EmpresaBean {
#Autowired
private EmpresaService empresaService;
private Empresa empresa;
private Empresa selectedEmpresa;
private List<Empresa> empresasSmall;
public EmpresaService getEmpresaService() {
return empresaService;
}
public Empresa getSelectedEmpresa() {
return selectedEmpresa;
}
public void setSelectedEmpresa(Empresa selectedEmpresa) {
this.selectedEmpresa = selectedEmpresa;
}
public void setEmpresaService(EmpresaService empresaService) {
this.empresaService = empresaService;
}
public EmpresaBean(){
empresa = new Empresa();
// empresasSmall=new ArrayList<Empresa>();
// list.add(new Empresa(getEmpresaList());
}
/*
public void addEmpresa(){
empresaService.add(empresa);
empresa = new Empresa();
} */
public List<Empresa> getEmpresaList(){
return empresaService.getAll();
}
public Empresa getEmpresa() {
return empresa;
}
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
}
You can not send html to another page (dialog). You should push only data, which will be used on another page.
To push data from datatable (which is considered to be a List) you should use #ManagedProperty annotation.
Assuming you have index page:
#ManagedBean(name="index")
#SessionScoped
public class IndexPage implements Serializable {
private List<String> values;
//getter and setter
}
and you have another page, where you would like to use that list:
#ManagedBean(name="nextPage")
#SessionScoped
public class AnotherPage implements Serializable {
#ManagedProperty(value="#{index.values}")
private List<String> forwardedList; //list with values form index page
//getter and setter
}
http://www.mkyong.com/jsf2/injecting-managed-beans-in-jsf-2-0/
UPD: if you would like to forward a row, but not a list, you should just make minor change in AnotherPage class:
#ManagedBean(name="nextPage")
#SessionScoped
public class AnotherPage implements Serializable {
#ManagedProperty(value="{empresaBean.selectedEmpresa}")
private Empresa selectedValue; //value from selected row in your table
//getter and setter
}

Displaying and editing Set values in PrimeFaces

I have JSF 2.2, PrimeFaces 3.5, Spring 3.1.3, Hibernate 4.1, MySQL web app.
On home.xhtml I have a tabview with 3 nested dataTables for 3 entities (Users, Computers, Applications) and CRUD buttons (see screenshot). Every button calls a dialog window with a form to add/edit/delete entity.
I will provide all code that is somehow associated with a problem (you may not need to check them all, I just made sure that every part of code you may be interested in is present below.)
Please, consider the following script for creating entities and their corresponding classes:
CREATE TABLE computers (
computer_id INT AUTO_INCREMENT,
computer_name VARCHAR(15) NOT NULL,
ip_address VARCHAR(15) NOT NULL UNIQUE,
login VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY(computer_id)
) ENGINE=InnoDB;
CREATE TABLE applications (
app_id INT AUTO_INCREMENT,
app_name VARCHAR(255) NOT NULL,
vendor_name VARCHAR(255) NOT NULL,
license_required TINYINT(1) NOT NULL,
PRIMARY KEY(app_id)
) ENGINE=InnoDB;
CREATE TABLE computer_app (
computer_id INT,
app_id INT,
FOREIGN KEY (computer_id)
REFERENCES computers(computer_id)
ON DELETE CASCADE,
FOREIGN KEY (app_id)
REFERENCES applications(app_id)
ON DELETE CASCADE
) ENGINE = InnoDB;
Computer.class:
#Entity
#Table(name="computers", catalog="adminportal")
public class Computer implements Serializable {
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="computer_id", unique=true, nullable=false)
private Integer computerId;
#Column(name="computer_name", nullable=false, length=15)
private String computerName;
#Column(name="ip_address", unique=true, nullable=false, length=15)
private String ipAddress;
#Column(name="login", nullable=false, length=20)
private String login;
#Column(name="password", nullable=false, length=20)
private String password;
#OneToMany(fetch=FetchType.EAGER, mappedBy="computers")
private Set<ComputerApp> computerApps = new HashSet<>(0);
Application.java:
#Entity
#Table(name="applications", catalog="adminportal")
public class Application implements Serializable {
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="app_id", unique=true, nullable=false)
private Integer appId;
#Column(name="app_name", nullable=false)
private String appName;
#Column(name="vendor_name", nullable=false)
private String vendorName;
#Column(name="license_required", nullable=false, columnDefinition = "BIT", length = 1)
private boolean licenseRequired;
#OneToMany(fetch=FetchType.LAZY, mappedBy="applications")
private Set<ComputerApp> computerApps = new HashSet<>(0);
ComputerApp.java
#Entity
#Table(name="computer_app" ,catalog="adminportal")
public class ComputerApp implements Serializable {
#EmbeddedId
#AttributeOverrides( {
#AttributeOverride(name="computerId", column=#Column(name="computer_id") ),
#AttributeOverride(name="appId", column=#Column(name="app_id") ) } )
private ComputerAppId id;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="app_id", insertable=false, updatable=false)
private Application applications;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="computer_id", insertable=false, updatable=false)
private Computer computers;
ComputerAppId.java:
#Embeddable
public class ComputerAppId implements Serializable {
#Column(name = "computer_id")
private Integer computerId;
#Column(name = "app_id")
private Integer appId;
home.xhtml:
<p:tabView id="tab" orientation="left">
<p:tab title="Users" rendered="#{request.isUserInRole('ROLE_ADMIN')}">
<h:form id="form1">
<h:panelGrid columns="9" >
<p:commandButton type="button" value="Add" onclick="dlg1.show()" />
<p:commandButton id="editUser" type="button" value="Edit" onclick="dlg2.show()" disabled="#{homeBean.selectedUser == null}"/>
<p:commandButton id="deleteUser" type="button" onclick="confirmation1.show()" value="Delete" disabled="#{homeBean.selectedUser == null}"/>
<p:confirmDialog id="delete1" header="Confirmation" widgetVar="confirmation1" >
<p:commandButton value="Yes" update=":tab:users" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation1.hide()" action="#{homeBean.deleteUser}" />
<p:commandButton value="No" onclick="confirmation1.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
<f:facet name="message">
<p:outputPanel>
<h:outputFormat value="#{homeBean.deleteUserMsg}"/>
</p:outputPanel>
</f:facet>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="users" var="user" value="#{homeBean.users}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedUser}" rowKey="#{user.userId}"
sortMode="single">
<p:ajax event="rowSelect" listener="#{homeBean.onUserRowSelect}" update=":tab:form1:deleteUser, :tab:form1:editUser, :tab:form1:delete1, :dlg2form:panel2"/>
<p:column headerText="Login" sortBy="#{user.login}">
<h:outputText value="#{user.login}"/>
</p:column>
<p:column headerText="Password" sortBy="#{user.password}">
<h:outputText value="#{user.password}"/>
</p:column>
<p:column headerText="Role" sortBy="#{user.role}">
<h:outputText value="#{user.role}"/>
</p:column>
<p:column headerText="Name" sortBy="#{user.firstName}">
<h:outputText value="#{user.firstName}"/>
</p:column>
<p:column headerText="Surname" sortBy="#{user.lastName}">
<h:outputText value="#{user.lastName}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:users" fileName="Users"/>
</p:tab>
<p:tab title="Computers">
<h:form id="form2">
<h:panelGrid columns="9" rendered="#{request.isUserInRole('ROLE_ADMIN')}">
<p:commandButton type="button" value="Add" onclick="dlg3.show()"/>
<p:commandButton id="editComp" type="button" value="Edit" onclick="dlg4.show()" disabled="#{homeBean.selectedComputer == null}"/>
<p:commandButton id="deleteComp" type="button" onclick="confirmation2.show()" value="Delete" disabled="#{homeBean.selectedComputer == null}"/>
<p:confirmDialog id="delete2" header="Confirmation"
severity="alert" widgetVar="confirmation2">
<p:commandButton value="Yes" update=":tab:computers" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation2.hide()" action="#{homeBean.deleteComputer}"/>
<p:commandButton value="No" onclick="confirmation2.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
<f:facet name="message">
<p:outputPanel>
<h:outputFormat value="#{homeBean.deleteCompMsg}"/>
</p:outputPanel>
</f:facet>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="computers" var="computer" value="#{homeBean.computers}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedComputer}" rowKey="#{computer.computerId}"
sortMode="single" >
<p:ajax event="rowSelect" listener="#{homeBean.onCompRowSelect}" update=":tab:form2:editComp, :tab:form2:deleteComp, :tab:form2:delete2, :dlg4form:panel4"/>
<p:column headerText="Login" sortBy="#{computer.login}">
<h:outputText value="#{computer.login}"/>
</p:column>
<p:column headerText="Password" sortBy="#{computer.password}">
<h:outputText value="#{computer.password}"/>
</p:column>
<p:column headerText="Name" sortBy="#{computer.computerName}" >
<h:outputText value="#{computer.computerName}"/>
</p:column>
<p:column headerText="IP address" sortBy="#{computer.ipAddress}">
<h:outputText value="#{computer.ipAddress}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:computers" fileName="Computers"/>
</p:tab>
<p:tab title="Applications">
<h:form id="form3" rendered="#{request.isUserInRole('ROLE_ADMIN')}">
<h:panelGrid columns="9">
<p:commandButton type="button" value="Add" onclick="dlg5.show()"/>
<p:commandButton id="editApp" type="button" value="Edit" onclick="dlg6.show()" disabled="#{homeBean.selectedApplication == null}"/>
<p:commandButton id="deleteApp" type="button" onclick="confirmation3.show()" value="Delete" disabled="#{homeBean.selectedApplication == null}"/>
<p:confirmDialog id="delete3" message="Are you sure you want to delete this application?" header="Confirmation"
severity="alert" widgetVar="confirmation3">
<p:commandButton value="Yes" update=":tab:applications" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation3.hide()" action="#{homeBean.deleteApplication}"/>
<p:commandButton value="No" onclick="confirmation3.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
<f:facet name="message">
<p:outputPanel>
<h:outputFormat value="#{homeBean.deleteAppMsg}"/>
</p:outputPanel>
</f:facet>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="applications" var="app" value="#{homeBean.applications}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedApplication}" rowKey="#{app.appId}"
sortMode="single" >
<p:ajax event="rowSelect" listener="#{homeBean.onAppRowSelect}" update=":tab:form3:editApp, :tab:form3:deleteApp, :tab:form3:delete3, :dlg6form:panel6"/>
<p:column headerText="Name" sortBy="#{app.appName}">
<h:outputText value="#{app.appName}"/>
</p:column>
<p:column headerText="Vendor" sortBy="#{app.vendorName}" >
<h:outputText value="#{app.vendorName}"/>
</p:column>
<p:column headerText="License required" sortBy="#{app.licenseRequired}">
<h:outputText value="#{app.licenseRequired}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:applications" fileName="Applications" />
</p:tab>
</p:tabView>
<!--DIALOGS ARE NOT PRESENT SINCE POST IS TOO LONG-->
</h:body>
</ui:component>
HomeBean.java:
#Component
#Scope("session")
public class HomeBean extends BaseBean {
private static final String editUserBtn = "tab:form1:editUser";
private static final String deleteUserBtn = "tab:form1:deleteUser";
private static final String editCompBtn = "tab:form2:editComp";
private static final String deleteCompBtn = "tab:form2:deleteComp";
private static final String editAppBtn = "tab:form3:editApp";
private static final String deleteAppBtn = "tab:form3:deleteApp";
private List<User> users;
private List<Computer> computers;
private List<Application> applications;
private User selectedUser, newUser;
private Computer selectedComputer, newComputer;
private Application selectedApplication, newApplication;
private String deleteUserMsg, deleteCompMsg, deleteAppMsg;
private RequestContext rc;
#PostConstruct
public void init() {
setUsers(hibernateDBManager.getAllUsers());
setComputers(hibernateDBManager.getAllComputers());
setApplications(hibernateDBManager.getAllApplications());
newUser = new User();
newComputer = new Computer();
newApplication = new Application();
rc = RequestContext.getCurrentInstance();
}
public void addUser() throws NoSuchAlgorithmException {
if (hibernateDBManager.insertUser(newUser)) {
users.add(newUser);
newUser = new User();
updateUserButtons();
}
}
public void editUser() throws NoSuchAlgorithmException {
if (hibernateDBManager.updateUser(selectedUser)) {
users.set(users.indexOf(selectedUser), selectedUser);
selectedUser = null;
updateUserButtons();
}
}
public void deleteUser() throws IOException {
if (selectedUser != null) {
if (hibernateDBManager.deleteUserById(selectedUser.getUserId()) > 0) {
users.remove(selectedUser);
selectedUser = null;
updateUserButtons();
}
}
}
public void addComputer() {
if (newComputer != null && hibernateDBManager.insertComputer(newComputer)) {
computers.add(newComputer);
newComputer = new Computer();
updateCompButtons();
}
}
public void editComputer() {
if (hibernateDBManager.updateComputer(selectedComputer)) {
computers.set(computers.indexOf(selectedComputer), selectedComputer);
selectedComputer = null;
updateCompButtons();
}
}
public void deleteComputer() {
if (selectedComputer != null) {
if (hibernateDBManager.deleteComputerById(selectedComputer.getComputerId()) > 0) {
computers.remove(selectedComputer);
selectedComputer = null;
updateCompButtons();
}
}
}
public void addApplication() {
if (newApplication != null && hibernateDBManager.insertApplication(newApplication)) {
applications.add(newApplication);
newApplication = new Application();
updateAppButtons();
}
}
public void editApplication() {
if (hibernateDBManager.updateApplication(selectedApplication)) {
applications.set(applications.indexOf(selectedApplication), selectedApplication);
selectedApplication = null;
updateAppButtons();
}
}
public void deleteApplication() {
if (selectedApplication != null) {
if (hibernateDBManager.deleteApplicationById(selectedApplication.getAppId()) > 0) {
applications.remove(selectedApplication);
selectedApplication = null;
updateAppButtons();
}
}
}
public void onUserRowSelect(SelectEvent event) {
setSelectedUser((User) event.getObject());
setDeleteUserMsg("Are you sure you want to delete user "
+ selectedUser.getFirstName() + " " + selectedUser.getLastName() + "?");
}
public void onCompRowSelect(SelectEvent event) {
setSelectedComputer((Computer) event.getObject());
deleteCompMsg = "Are you sure you want to delete computer "
+ selectedComputer.getComputerName()
+ " (" + selectedComputer.getIpAddress() + ") ?";
}
public void onAppRowSelect(SelectEvent event) {
setSelectedApplication((Application) event.getObject());
deleteAppMsg = "Are you sure you want to delete application "
+ selectedApplication.getAppName() + "?";
}
protected void updateUserButtons() {
rc.update(editUserBtn);
rc.update(deleteUserBtn);
}
protected void updateCompButtons() {
rc.update(editCompBtn);
rc.update(deleteCompBtn);
}
protected void updateAppButtons() {
rc.update(editAppBtn);
rc.update(deleteAppBtn);
}
//Getters/setters
}
My target is to find the best way to display Set values (Set in Computer) in a dataTable or somehow else manage adding and removing applications from/to selected computers.
Every answer is highly appreciated and responded quickly!
Thank you.
In the end I used PrimeFaces's <picklist> element as a best approach in my issue.

Using Selection on dataTable primefaces

I have a problem in primefaces using datatable.
I use the propertie selection but i can't take the object that I selected.
Take a look at my code
<p:dataTable id="dtProdutos" value="#{produtoBean.produtos}" var="p"
emptyMessage="Nenhum registro encontrado." selectionMode="single"
selection="#{produtoBean.selectedProduto}" rowKey="#{p.id}"
style="text-align: center; font-weight: bold;" >
<f:facet name="header">
<h:outputText value="Registro de Produtos" />
</f:facet>
<p:column>
<h:outputText value="#{p.id}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Nome" />
</f:facet>
<h:outputText value="#{p.nome}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Descrição" />
</f:facet>
<h:outputText value="#{p.descricao}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Valor Un." />
</f:facet>
<h:outputText value="#{p.valorUnitario}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Remover" />
</f:facet>
<f:ajax event="click" render="#form"
listener="#{produtoBean.remove(p)}">
<h:commandLink value="Remover" />
</f:ajax>
</p:column>
<f:facet name="footer">
<p:commandButton id="updateButton" value="Update" icon="ui-icon-search"
update=":frmGeral:display" oncomplete="produtoDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog id="dialog" header="Alterar" widgetVar="produtoDialog" resizable="false"
width="200" showEffect="clip" hideEffect="fold">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Nome" />
<h:outputText value="#{produtoBean.selectedProduto.nome}" />
</h:panelGrid>
</p:dialog>
My Managed Bean
#ManagedBean
public class ProdutoBean{
#ManagedProperty(value = "#{entityManager}")
private EntityManager entityManager = Persistence.createEntityManagerFactory("PrimeiroTeste").createEntityManager();
private Produto produto = new Produto();
private List<Produto> produtos;
private Produto selectedProduto = new Produto();
public void save(){
ProdutoRepository produtoRepository = new ProdutoRepository(this.entityManager);
produtoRepository.save(this.produto);
this.produto = new Produto();
this.produtos = null;
}
public void remove(Produto produto){
ProdutoRepository produtoRepository = new ProdutoRepository(this.entityManager);
produtoRepository.remove(produto);
this.produtos = null;
}
public List<Produto> getProdutos(){
if (this.produtos == null){
ProdutoRepository produtoRepository = new ProdutoRepository(this.entityManager);
this.produtos = produtoRepository.getProdutos();
}
return this.produtos;
}
public Produto getProduto(){
return this.produto;
}
public void setProduto(Produto produto){
this.produto = produto;
}
public void setEntityManager(EntityManager entityManager){
this.entityManager = entityManager;
}
#SuppressWarnings("unused")
private EntityManager getManager() {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) ec.getRequest();
return (EntityManager) request.getAttribute(" EntityManager ");
}
public Produto getSelectedProduto() {
return this.selectedProduto;
}
public void setSelectedProduto(Produto selectedProduto) {
this.selectedProduto = selectedProduto;
}
}
When I open my dialog it don't bring the selectedProduto.nome
Someone can help me?
Take a look at the Primefaces ShowCase
You always create a new Product for your selectedProduto
private Produto selectedProduto = new Produto();
try it with this code:
private Produto selectedProduto;
the getters and setters are already there as is saw.

How to redirect primefaces wizard to first tab after submit on last tab

I am using primefaces 3.2. I have prepared wizard which insert user information on same page in datatable. Wizard get information tab by tab and submitted on confirmation tab. Also it will reflected on same page on datatable. It is working fine. Now I need to update multiple users. For that I have to navigate wizard from submit button to first tab.
Any help will be appreciated.
My code is as below
wizard.xhtml
<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>Wizard Example</title>
<script type="text/javascript" >
function resetWizard() {
wiz.loadStep(wiz.cfg.steps[0], true);
}
</script>
</h:head>
<h:body>
<h:form id="form">
<!-- <p:growl id="growl" sticky="true" showDetail="true"/> -->
<p:growl redisplay="false" life="3000" id="mymessage" autoUpdate="true"/>
<p:wizard widgetVar="wiz"
flowListener="#{userWizard.onFlowProcess}" showNavBar="true" >
<p:tab id="personal" title="Personal" >
<p:panel header="Personal Details">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value" styleClass="grid">
<h:outputText value="Firstname: *" />
<p:inputText required="true" label="Firstname"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: *" />
<p:inputText required="true" label="Lastname"
value="#{userWizard.user.lastname}" />
<h:outputText value="Age: " />
<p:inputText value="#{userWizard.user.age}" />
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="address" title="Address" >
<p:panel header="Adress Details">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:outputText value="Street: " />
<p:inputText value="#{userWizard.user.street}" />
<h:outputText value="Postal Code: " />
<p:inputText value="#{userWizard.user.postalCode}" />
<h:outputText value="City: " />
<p:inputText value="#{userWizard.user.city}" />
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="contact" title="Contact" >
<p:panel header="Contact Information">
<h:messages errorClass="error"/>
<h:panelGrid columns="2" columnClasses="label, value">
<h:outputText value="Email: *" />
<p:inputText required="true" label="Email"
value="#{userWizard.user.email}" />
<h:outputText value="Phone: " />
<p:inputText value="#{userWizard.user.phone}"/>
<h:outputText value="Additional Info: " />
<p:inputText value="#{userWizard.user.info}"/>
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab id="confirm" title="Confirmation" >
<p:panel header="Confirmation">
<h:panelGrid id="confirmation" columns="6">
<h:outputText value="Firstname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.firstname}" />
<h:outputText value="Lastname: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.lastname}"/>
<h:outputText value="Age: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.age}" />
<h:outputText value="Street: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.street}" />
<h:outputText value="Postal Code: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.postalCode}" />
<h:outputText value="City: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.city}" />
<h:outputText value="Email: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.email}" />
<h:outputText value="Phone " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.phone}"/>
<h:outputText value="Info: " />
<h:outputText styleClass="outputLabel"
value="#{userWizard.user.info}" />
</h:panelGrid>
<p:commandButton immediate="true" value="Submit" update="wiz"
actionListener="#{userWizard.save}" ajax="false"/>
</p:panel>
</p:tab>
</p:wizard>
<p:dataTable var="user" value="#{userWizard.userAll}" id="userList" editable="true" rowKey="#{user.firstname}" paginator="true"
rows="4" rowsPerPageTemplate="4,6" >
<p:column headerText="FirstName" style="width:125px" filterBy="#{user.firstname}" sortBy="#{user.firstname}">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{user.firstname}" />
</f:facet>
<f:facet name="input">
<h:outputText value="#{user.firstname}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="LastName" style="width:125px" filterBy="#{user.lastname}" sortBy="#{user.lastname}" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{user.lastname}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{user.lastname}" style="width:100%" >
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Age" style="width:125px" filterBy="#{user.age}" sortBy="#{user.age}">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{user.age}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{user.age}" style="width:100%" >
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Edit" style="width:50px">
<p:rowEditor />
</p:column>
<p:ajax event="rowEdit" listener="#{userWizard.editRowListner}" update=":form:mymessage"/>
</p:dataTable>
</h:form>
</h:body>
UserWizard.java
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.faces.bean.SessionScoped;
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;
import org.primefaces.event.FlowEvent;
import org.primefaces.event.RowEditEvent;
#ManagedBean
#SessionScoped
public class UserWizard {
private User user = new User();
private boolean skip;
private List<User> userAll = new ArrayList<User>();
private static Logger logger = Logger.getLogger(UserWizard.class.getName());
/*public UserWizard() {
userAll = new ArrayList<User>();
}*/
public List<User> getUserAll() {
return userAll;
}
public void setUserAll(List<User> userAll) {
this.userAll = userAll;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void save(ActionEvent actionEvent) {
//Persist user
System.out.println("First name : " + user.getFirstname());
System.out.println("Last name : " + user.getLastname());
System.out.println("Age name : " + user.getAge());
userAll.add(user);
user = new User();
FacesMessage msg = new FacesMessage("Successful", "Welcome :" + user.getFirstname());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public boolean isSkip() {
return skip;
}
public void setSkip(boolean skip) {
this.skip = skip;
}
public String onFlowProcess(FlowEvent event) {
logger.info("Current wizard step:" + event.getOldStep());
logger.info("Next step:" + event.getNewStep());
System.out.println("First name : " + user.getFirstname());
System.out.println("Last name : " + user.getLastname());
System.out.println("Age name : " + user.getAge());
if (skip) {
skip = false; //reset in case user goes back
return "confirm";
} else {
return event.getNewStep();
}
}
public void editRowListner(RowEditEvent rowEditEvent) {
try {
User updatedUser = (User) rowEditEvent.getObject();
System.out.println("User First Name: " + updatedUser.getFirstname());
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Update called", "updated by user"));
} catch (Exception ex) {
ex.getMessage();
}
}
}
User.java
public class User {
private String firstname;
private String lastname;
private Integer age;
private String street;
private String city;
private String postalCode;
private String info;
private String email;
private String phone;
public User(String firstname, String lastname, Integer age, String street, String city, String postalCode, String info, String email, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.street = street;
this.city = city;
this.postalCode = postalCode;
this.info = info;
this.email = email;
this.phone = phone;
}
public User() {
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
In the wizard.xhtml page change your submit button to :
<p:commandButton immediate="true" value="Submit" update="#parent,:form:userList" actionListener="#{userWizard.save}" oncomplete="wiz.loadStep (wiz.cfg.steps [0], true)"/>
you can also do it from Java code as follow:
Wizard wizard = (Wizard) FacesContext.getCurrentInstance().getViewRoot().findComponent("importForm:wizardId");
wizard.setStep(STEP1);
RequestContext.getCurrentInstance().update("importForm");
In primefaces 5 you can't call widgetVar directly, you need to call it like PF('widgetVar') so you can do it like this :
<p:commandButton value="Submit" actionListener="#{userWizard.save}" oncomplete="PF('wiz').loadStep('tabId',false)" />