Primefaces DataTable - Complex example: No value on selected row - jsf-2

I'm trying execute the DataTable example avaiable on Primefaces Showcase. All functions works but when i select a row, the value of the selected row isn't displayed on my <p:dialog>.
I've already checked all alternatives and nothing works. Could someone help me?
I'm using Primefaces 3.3 and glassfish 3.0.1. Here goes my code:
dataTableComplex.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<body>
<h:form id="form">
<p:dataTable var="car" value="#{tableBean.cars}" rowKey="#{car.model}" paginator="true" rows="10"
selection="#{tableBean.selectedCar}" selectionMode="single" id="carsTable">
<p:ajax event="rowSelect" update=":form:display" oncomplete="carDialog.show()" />
<f:facet name="header">
List of Cars
</f:facet>
<p:column headerText="Model" sortBy="#{car.model}" filterBy="#{car.model}" id="model">
#{car.model}
</p:column>
<p:column headerText="Year" sortBy="#{car.year}" filterBy="#{car.year}" id="year">
#{car.year}
</p:column>
<p:column headerText="Manufacturer" sortBy="#{car.manufacturer}" filterBy="#{car.manufacturer}" id="manufacturer">
#{car.manufacturer}
</p:column>
<p:column headerText="Color" sortBy="#{car.color}" filterBy="#{car.color}" id="color">
#{car.color}"
</p:column>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="carDialog" resizable="false"
width="200" showEffect="explode" hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Model:" />
<h:outputText value="#{tableBean.selectedCar.model}" id="model"/>
<h:outputText value="Year:" />
<h:outputText value="#{tableBean.selectedCar.year}" id="year"/>
<h:outputText value="Manufacturer:" />
<h:outputText value="#{tableBean.selectedCar.manufacturer}" id="manufacturer"/>
<h:outputText value="Color:" />
<h:outputText value="#{tableBean.selectedCar.color}" id="color"/>
</h:panelGrid>
</p:dialog>
</h:form>
</body>
</html>
TableBean.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ViewScoped
#ManagedBean(name = "tableBean")
#SessionScoped
public class TableBean implements Serializable {
private final static String[] colors;
private final static String[] manufacturers;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
manufacturers = new String[10];
manufacturers[0] = "Mercedes";
manufacturers[1] = "BMW";
manufacturers[2] = "Volvo";
manufacturers[3] = "Audi";
manufacturers[4] = "Renault";
manufacturers[5] = "Opel";
manufacturers[6] = "Volkswagen";
manufacturers[7] = "Chrysler";
manufacturers[8] = "Ferrari";
manufacturers[9] = "Ford";
}
private List<Car> cars;
private Car selectedCar;
private Car[] selectedCars;
public TableBean() {
cars = new ArrayList<Car>();
populateRandomCars(cars, 50);
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
private void populateRandomCars(List<Car> list, int size) {
for(int i = 0 ; i < size ; i++)
list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomManufacturer() {
return manufacturers[(int) (Math.random() * 10)];
}
private String getRandomModel() {
return UUID.randomUUID().toString().substring(0, 8);
}
public List<Car> getCars() {
return cars;
}
}
Car.java
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "car")
#SessionScoped
public class Car implements Serializable {
private String model;
private int year;
private String manufacturer;
private String color;
private int price;
public Car(){
}
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public Car(String model, int year, String manufacturer, String color, int price) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
#Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Car))
return false;
Car compare = (Car) obj;
return compare.model.equals(this.model);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + model.hashCode();
}
#Override
public String toString() {
return "Car{" + "model=" + model + ", year=" + year + ", manufacturer=" + manufacturer + ", color=" + color + ", price=" + price + '}';
}
}
Edited: to solve this problem just add #ViewScoped on TableBean.java.

Your TableBean should be ViewScoped.
Add #ViewScoped on top of TableBean or configure it using faces-config.xml file.

You are using the example from the Showcase Labs, which is running on PrimeFaces version 3.4 (still in development at time of posting).
Since you are using PrimeFaces 3.3, you should be using the examples from the common Showcase.
Remember that the Labs version of the Showcase is always running on the still-on-development versions, while the common Showcase is always on the lastest final release.
You can always see what version is running behind the Showcase by checking the bottom of the page.

Since class Car is just a common class, not a manage bean, You don't need the declaration:
#ManagedBean(name = "car")
#SessionScoped

Related

Shopping Cart does not display updated info

I'm using WildFly 9.0 and IntelliJ 14 Ultimate
I can add items to the cart- and they can be viewed using a PrimeFaces data table on ViewCart.xhtml
There is a button to delete each cart item- which works.
Faces-config has been edited to return back to the ViewCart.xhtml page when the button is clicked; which seems to be the case.
The PROBEM: Cart is still showing the original list, before the item was deleted.
If I go to the product catalogue and return back to ViewCart.xhtml, the executed changes are reflected in the cart. Please can someone help?
Here is the ViewCart.xhtml page
<body>
<h:outputText value="Cart List"
style="font-family: Verdana, Helvetica, sans-serif;font-size: 18px; font-weight: 900;" />
<h:form name="ViewProductsManagedBean">
<p:dataTable id="cartTable" var="cartList"
value="#{ViewProductsManagedBean.cart}" <p:column>
<f:facet name="header">
<h:outputText value="Delete Cart Item "
style="font-family: Verdana, Helvetica, sans-serif;font-size: 16px;" />
</f:facet>
<h:commandButton action="#{ViewProductsManagedBean.removeItemFromCart(cartList.itemcode)}"> </h:commandButton>
</p:column>
</f:facet>
</p:dataTable>
</h:form>
</body>
</html>
now the managed bean:
#ManagedBean(name="ViewProductsManagedBean")
#RequestScoped
public class ViewProductsManagedBean {
public String removeItemFromCart(String itemCode){
return cartFunctions.removeItemFromCart(itemCode);
}
}
The facade that "talks" to the business logic
#Stateful
#SessionScoped
public class CartFacade {
public String removeItemFromCart(String itemCode){
return cartBean.removeItemFromCart(itemCode);
}
}
The cart been looks like follows:
#Stateful
#Local(ShoppingCartLocal.class)
#Remote(ShoppingCart.class)
#SessionScoped
public class ShoppingCartBean implements ShoppingCartLocal, ShoppingCart {
public String removeItemFromCart(String itemCode){
for(Orderitem ord:cartItems){
if(itemCode.equals(ord.getItemcode())){
cartItems.remove(ord);
System.out.println("Item removed " + itemCode);
}
}
return "ViewCart";
}
here is the full cart bean
package com.shop.cart;
/**
* Created by LalinPethiyagoda on 30/07/2015.
*/
#Stateful
#Local(ShoppingCartLocal.class)
#Remote(ShoppingCart.class)
#SessionScoped
public class ShoppingCartBean implements ShoppingCartLocal, ShoppingCart {
#PersistenceContext(unitName ="Shop")
private EntityManager cartEntityManager;
private CustomerManager customerManagerBean;
private CopyOnWriteArrayList<Orderitem> cartItems = new CopyOnWriteArrayList<>();
private List<Orderitem> cartItemsReturn = new ArrayList<>();
public void setCartItems(CopyOnWriteArrayList<Orderitem> cartItems) {
this.cartItems = cartItems;
}
private CustomerEntity customer;
public ShoppingCartBean(){}
#Override
public List<Orderitem> getCartItemsReturn() {
return cartItemsReturn;
}
public void setCartItemsReturn(List<Orderitem> cartItemsReturn) {
this.cartItemsReturn = cartItemsReturn;
}
#Override
public boolean addCartItem(ProductEntity product, int quantityPurchased){
com.shop.entity.Orderitem basketItem=new Orderitem();
Locale currentLocale = new Locale("en", "GB");
double subTotal;
// check for duplicate entry.
for (Orderitem itemsIntheCart : cartItems) {
if (itemsIntheCart.getItemcode().equals(product.getItemcode())) {
return false;
}
}
basketItem.setItemcode(product.getItemcode());
basketItem.setItemdescription(product.getItemdescription());
basketItem.setUnitprice(product.getUnitprice());
basketItem.setQuantitypurchased(quantityPurchased);
subTotal = quantityPurchased * basketItem.getUnitprice();
Double currencyAmount = new Double(subTotal);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
currencyFormatter.format(currencyAmount);
basketItem.setSubtotal(currencyAmount);
cartItems.add(basketItem);
return true;
}
public String removeItemFromCart(String itemCode){
for(Orderitem ord:cartItems){
if(itemCode.equals(ord.getItemcode())){
cartItems.remove(ord);
System.out.println("Item removed " + itemCode);
}
}
return "ViewCart";
}
#Override
public CopyOnWriteArrayList<Orderitem> viewCartItems(){
return this.cartItems;
}
#Override
public CopyOnWriteArrayList<Orderitem> getCartItems(){
CopyOnWriteArrayList<Orderitem> cartItemList = this.cartItems;
for(Orderitem x:cartItemList){
System.out.println(x.getItemdescription());
}
return cartItemList;
}
public CustomerEntity getCustomer() {
return customer;
}
public void setCustomer(CustomerEntity customer) {
this.customer = customer;
}
public void removeCartItem(int itemCode){
System.out.println("hello");
}
#Override
public double getTotal(){
double total=0;
for(Orderitem bItem:getCartItems()){
total = total + bItem.getSubtotal();
}
return total;
}
#PreDestroy
public void exit(){
persistCartItems();
stopSession();
}
#Override
public void persistCartItems() {
// TODO Auto-generated method stub
}
#Remove
public void stopSession(){
System.out.println("saved- all done - object detached from object pool");
}
public void assignCartToCustomer(){
customer = customerManagerBean.getVerifiedCustomer();
}
public CustomerEntity getCustomerAssociatedWithTheCart(){
return this.customer;
}
#Remove
public void remove() {
cartItems = null;
}
#Override
public void incrementQuantity() {
}
#Override
public void decrementQuantity() {
}
}

DataTable - Selection RadioButton Primefaces 5 not work?

Hi community I have a query with radio button selection in datatable of primefaces 5, when I click to register and invoke the event to edit, not capturing the registry value returns me null object.
My code xhtml:
<p:dataTable id="tblProductos" var="producto"
value="#{cBusquedaProducto.lazyDataProductos}"
rowIndexVar="rowIndex" lazy="true" rows="10"
paginator="true" paginatorPosition="top"
rowKey="#{producto.icodProducto}"
selectionMode="single"
selection="#{cBusquedaProducto.producto}"
emptyMessage="#{msg['tabla.noExistenRegistros']}"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
currentPageReportTemplate="Registros: {totalRecords} - [ {currentPage} de {totalPages} ]"
rowsPerPageTemplate="10,20,30,40,50,200">
<p:column selectionMode="single" />
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="#{msg['form.item']}" />
</f:facet>
<h:outputText value="#{rowIndex + 1}" />
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="#{msg['form.codigo']}" />
</f:facet>
<h:outputText value="#{producto.icodProducto}" />
</p:column>
<p:column style="text-align: center;">
<f:facet name="header">
<h:outputText value="#{msg['form.descripcion']}" />
</f:facet>
<h:outputText value="#{producto.vdesProducto}" />
</p:column>
.......
</p:dataTable>
Controller:
#ManagedBean(name = "cBusquedaProducto")
#ViewScoped
public class CBusquedaProducto extends BaseController {
#ManagedProperty(value = "#{iProductoService}")
private IProductoService iProductoService;
private LazyDataModel<ProductoBean> lazyDataProductos;
#PostConstruct
#Override
public void inicializarObjetos() {
try {
/* Cargamos las listas */
Map<String, Serializable> filters = new HashMap<String, Serializable>();
filters.put("param.icodEmpresa", Constantes.ONE_INT);
this.lazyDataProductos = new ProductoLazyDataModel(iProductoService, filters);
this.opcProducto = Constantes.ONE_SHORT;
} catch (Exception e) {
LOGGER.error(getGenerarError(
Thread.currentThread().getStackTrace()[1].getMethodName(),
Constantes.NIVEL_APP_CONSTROLLER,
this.getClass().getName(), e.getMessage()));
}
}
... get and set
}
LazyDataModel:
public class ProductoLazyDataModel extends LazyDataModel<ProductoBean> {
private static final long serialVersionUID = 1L;
public Logger logger = LoggerFactory.getLogger(this.getClass());
private List<ProductoBean> datasource;
Map<String, Serializable> extFilters = new HashMap<String, Serializable>();
private int pageSize;
private int rowIndex;
private int rowCount;
private IProductoService iProductoService;
/**
* #param iProductoService - El servicio para obtener datos desde base de datos.
* #param extFilters - Los filtros a aplicar a las columnas, acepta nulo.
*/
public ProductoLazyDataModel(IProductoService iProductoService,
Map<String, Serializable> extFilters) {
this.iProductoService = iProductoService;
this.extFilters = extFilters;
}
#Override
public List<ProductoBean> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, Object> filters) {
try {
SortCriteria sort = new SortCriteria();
if (sortField == null) {
sort.add("icodProducto", false);
} else {
if (sortOrder == SortOrder.ASCENDING) {
sort.add(sortField, true);
} else {
sort.add(sortField, false);
}
}
WrappedData<ProductoBean> wd = iProductoService.obtenerProductos(filters,
extFilters, sort, first, pageSize);
datasource = wd.getData();
setRowCount(wd.getRowCount().intValue());
} catch (Exception e) {
logger.error(e.toString());
}
return datasource;
}
#Override
public boolean isRowAvailable() {
if (datasource == null)
return false;
int index = rowIndex % pageSize;
return index >= 0 && index < datasource.size();
}
#Override
public Object getRowKey(ProductoBean gr) {
return gr.getIcodProducto();
}
#Override
public ProductoBean getRowData() {
if (datasource == null)
return null;
int index = rowIndex % pageSize;
if (index > datasource.size()) {
return null;
}
return datasource.get(index);
}
#Override
public ProductoBean getRowData(String rowKey) {
if (datasource == null)
return null;
for (ProductoBean gr : datasource) {
String cod = String.valueOf(gr.getIcodProducto());
if (cod.equals(rowKey)) {
return gr;
}
}
return null;
}
#Override
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
#Override
public int getPageSize() {
return pageSize;
}
#Override
public int getRowIndex() {
return this.rowIndex;
}
#Override
public void setRowIndex(int rowIndex) {
this.rowIndex = rowIndex;
}
#Override
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
#Override
public int getRowCount() {
return this.rowCount;
}
#SuppressWarnings("unchecked")
#Override
public void setWrappedData(Object list) {
this.datasource = (List<ProductoBean>) list;
}
#Override
public Object getWrappedData() {
return datasource;
}
}
Hope you can help me, because I find the reason, I've tried with chekbox and with that if it works but with radiobutton not working ....

Not able to display dialog contents when selection is enabled in primefaces datatable

I am trying to display dialog popup containing input text area on click of a command button in one of the column using the approach shown in showcase example .In my case the datatable is a multiple selection enabled with the implementation of datamodel.The pop-up with text area only appears when the datatable has same feature as shown in the showcase but when multiple selection is implemented (with or without datamodel implementation)nothing gets displayed in the text area and i get the following exception when i check a row and click on the command button.When i directly click on command button no exception is thrown.
javax.faces.FacesException
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:86)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:508)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at com.gaic.datamodel.CarDataModel.getRowData(CarDataModel.java:27)
at com.gaic.datamodel.CarDataModel.getRowData(CarDataModel.java:1)
at org.primefaces.component.datatable.DataTable.getRowData(DataTable.java:953)
at org.primefaces.component.datatable.feature.SelectionFeature.decodeMultipleSelection(SelectionFeature.java:71)
at org.primefaces.component.datatable.feature.SelectionFeature.decode(SelectionFeature.java:40)
at org.primefaces.component.datatable.DataTableRenderer.decode(DataTableRenderer.java:57)
at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:796)
at org.primefaces.component.api.UIData.processDecodes(UIData.java:228)
at javax.faces.component.UIForm.processDecodes(UIForm.java:216)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1048)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1048)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:926)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
... 15 more
My JSF page snippet
<h:body>
<h:form id="form">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="cars" var="car" value="#{tableBean.mediumCarsModel}"
selection="#{tableBean.selectedCars}">
<p:column selectionMode="multiple" style="width:2%" />
<p:column headerText="Model" style="width:24%">
<h:outputText value="#{car.model}" />
</p:column>
<p:column headerText="Year" style="width:24%">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Manufacturer" style="width:24%">
<h:outputText value="#{car.manufacturer}" />
</p:column>
<p:column headerText="Color" style="width:24%">
<h:outputText value="#{car.color}" />
</p:column>
<p:column style="width:4%">
<p:commandButton id="selectButton" update=":form:display"
oncomplete="carDialog.show()" icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{car}"
target="#{tableBean.selectedCar}" />
</p:commandButton>
</p:column>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="carDialog" resizable="false"
id="carDlg" showEffect="fade" hideEffect="explode" modal="true">
<p:dataList id="display" value="#{tableBean.selectedCar}"
var="selectedWorkSpaceItem"
style="border: 0px solid gray;padding-bottom:1px;">
<p:inputTextarea value="#{selectedWorkSpaceItem.color}">
</p:inputTextarea>
</p:dataList>
</p:dialog>
</h:form>
My managed bean
public class TableBean implements Serializable {
private final static String[] colors;
private final static String[] manufacturers;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
manufacturers = new String[10];
manufacturers[0] = "Mercedes";
manufacturers[1] = "BMW";
manufacturers[2] = "Volvo";
manufacturers[3] = "Audi";
manufacturers[4] = "Renault";
manufacturers[5] = "Opel";
manufacturers[6] = "Volkswagen";
manufacturers[7] = "Chrysler";
manufacturers[8] = "Ferrari";
manufacturers[9] = "Ford";
}
private List<Car> cars;
private Car selectedCar;
private CarDataModel mediumCarsModel;
private Car[] selectedCars;
public TableBean() {
cars = new ArrayList<Car>();
populateRandomCars(cars, 50);
mediumCarsModel = new CarDataModel(cars);
}
private void populateRandomCars(List<Car> list, int size) {
for (int i = 0 ; i < size ; i++)
list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public List<Car> getCars() {
return cars;
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomManufacturer() {
return manufacturers[(int) (Math.random() * 10)];
}
private String getRandomModel() {
return UUID.randomUUID().toString().substring(0, 8);
}
public CarDataModel getMediumCarsModel() {
if(mediumCarsModel==null) {
System.out.println("yes it is null!!!!!!");
mediumCarsModel = new CarDataModel(cars);
}
return mediumCarsModel;
}
public void setMediumCarsModel(CarDataModel mediumCarsModel) {
this.mediumCarsModel = mediumCarsModel;
}
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car[] selectedCars) {
this.selectedCars = selectedCars;
}
}
Is there any way using which i can display the content in dialog text area?
Are you using #annotations to mark your beans? Or faces-config.xml file? Try to annotate your bean with #ManagedBean and #ViewScoped. Take a look in this J2EE 6 documentation too.
#ManagedBean
#ViewScoped
public class TableBean implements Serializable {
private final static String[] colors;
private final static String[] manufacturers;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
manufacturers = new String[10];
manufacturers[0] = "Mercedes";
manufacturers[1] = "BMW";
manufacturers[2] = "Volvo";
manufacturers[3] = "Audi";
manufacturers[4] = "Renault";
manufacturers[5] = "Opel";
manufacturers[6] = "Volkswagen";
manufacturers[7] = "Chrysler";
manufacturers[8] = "Ferrari";
manufacturers[9] = "Ford";
}
private List<Car> cars;
private Car selectedCar;
private CarDataModel mediumCarsModel;
private Car[] selectedCars;
public TableBean() {
cars = new ArrayList<Car>();
populateRandomCars(cars, 50);
mediumCarsModel = new CarDataModel(cars);
}
private void populateRandomCars(List<Car> list, int size) {
for (int i = 0 ; i < size ; i++)
list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public List<Car> getCars() {
return cars;
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomManufacturer() {
return manufacturers[(int) (Math.random() * 10)];
}
private String getRandomModel() {
return UUID.randomUUID().toString().substring(0, 8);
}
public CarDataModel getMediumCarsModel() {
if(mediumCarsModel==null) {
System.out.println("yes it is null!!!!!!");
mediumCarsModel = new CarDataModel(cars);
}
return mediumCarsModel;
}
public void setMediumCarsModel(CarDataModel mediumCarsModel) {
this.mediumCarsModel = mediumCarsModel;
}
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car[] selectedCars) {
this.selectedCars = selectedCars;
}
}
1.You need to add rowKey in your dataTable.
<p:dataTable id="cars" var="car" rowKey="#{car.model}" value="#{tableBean.mediumCarsModel}"
selection="#{tableBean.selectedCars}">
2.You need to have one button say in the header of the datatable which you'll click to display the dialog. Since your are selecting multiple rows, then you don't need a button on each row as shown in the example.
<f:facet name="header">
<p:commandButton value="Click" onclick="PF('carDialog').show();" update=":form:display" />
</f:facet>
3.What data would you want to display in your dialog TextArea? The datatable has multiple columns i.e Model, Year, Manufacturer, Color. You might want to change the component from textArea to any component that displays a list e.g dataList or datatable in your dialog.

PrimeFaces DataTable with required Radiobutton

I am using PrimeFaces DataTable with Radiobuttons inside a one wizard tab. Is possible to somehow set Radiobuttons like required?
User shouldn't go to the next wizard tab until he will choose one option in DataTable with Radiobuttons.
Or have you any ideas how to resolve this problem? Thanks for any replies!
JSP page
<p:tab id="test" title="Test">
<p:panel header="Term page">
<p:dataTable id="collection" value="#{register.dataList}" var="dl" rowKey="#{dl.c_id}" selection="#{register.selectedTerm}"">
<p:column selectionMode="single" style="width:2%" />
<p:column>
#{dl.c_id}
</p:column>
</p:dataTable>
</p:panel>
</p:tab>
You can check for data selection in flowListener of <p:wizard> tag that is triggered when next/previous buttons are clicked and conditionally add FacesMessage:
public String onFlowProcess(FlowEvent event) {
String current = event.getOldStep();
String next = event.getNewStep();
boolean proceed = true;
if(current.equals("first") && next.equals("second") && (selectedData == null)) {
//proceed only when data was selected and user is moving to the next step
FacesMessage facesMessage = new FacesMessage("You need to make a selection in a datatable to proceed!");
FacesContext.getCurrentInstance().addMessage("form:selection", facesMessage);
proceed = false;
}
return proceed ? next : current;
}
The full example is provided below.
The view:
<h:form id="form">
<p:wizard widgetVar="wiz" flowListener="#{q16439053Bean.onFlowProcess}">
<p:tab id="first" title="First">
<p:message for="selection"/>
<p:panel id="selection" header="Term page">
<p:dataTable id="collection" value="#{q16439053Bean.list}" var="data" rowKey="#{data.name}" selection="#{q16439053Bean.selectedData}">
<p:column selectionMode="single" style="width:2%" />
<p:column>
#{data.name}
</p:column>
</p:dataTable>
</p:panel>
</p:tab>
<p:tab id="second" title="Second">
Done!
</p:tab>
</p:wizard>
</h:form>
The bean:
#ManagedBean
#ViewScoped
public class Q16439053Bean implements Serializable {
private List<Data> list;
private Data selectedData;
public List<Data> getList() {
return list;
}
public void setList(List<Data> list) {
this.list = list;
}
public Data getSelectedData() {
return selectedData;
}
public void setSelectedData(Data selectedData) {
this.selectedData = selectedData;
}
public class Data {
private String name;
private String value;
public Data() {
}
public Data(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public Q16439053Bean() {
list = new ArrayList<Data>();
Data d;
d = new Data("name", "value");
list.add(d);
d = new Data("name1", "value1");
list.add(d);
d = new Data("name2", "value2");
list.add(d);
d = new Data("name3", "value3");
list.add(d);
}
public String onFlowProcess(FlowEvent event) {
String current = event.getOldStep();
String next = event.getNewStep();
boolean proceed = true;
if(current.equals("first") && next.equals("second") && (selectedData == null)) {
FacesMessage facesMessage = new FacesMessage("You need to make a selection in a datatable to proceed!");
FacesContext.getCurrentInstance().addMessage("form:selection", facesMessage);
proceed = false;
}
return proceed ? next : current;
}
}

on clicking a4j:commandbutton, method does not get executed

I am developing an application using jsf2.0, richfaces 4.0, tomcat 6.0. On a page I am trying to delete a row . But when I click the delete icon, sometimes popup panel does not appear and when it is shown , nothing happens on clicking the delete button.
Following is my .xhtml file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<ui:composition template="template.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="meetingId" required="true" value="#{meetingBean.selectedMeetId}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h3>List of Employees in selected meeting</h3>
<a4j:status onstart="#{rich:component('statPane')}.show()"
onstop="#{rich:component('statPane')}.hide()" />
<h:form>
<c:if test="#{! empty meetingBean.selectedMeeting}">
<c:set target="#{flash}" property="selectedMeeting"
value="#{meetingBean.selectedMeeting}" />
</c:if>
<c:if test="#{! empty flash.selectedMeeting}">
<c:set target="#{meetingBean}" property="selectedMeeting"
value="#{flash.selectedMeeting}" />
</c:if>
<rich:extendedDataTable value="#{meetingBean.selectedMeeting.employees}" var="empMeet" border="1" id="table">
<rich:column>
<f:facet name="header">Employee Id</f:facet>
#{empMeet.empId}
</rich:column>
<rich:column>
<f:facet name="header"> Employee Name</f:facet>
#{empMeet.firstName} #{empMeet.lastName}
</rich:column>
<rich:column>
<a4j:commandLink execute="#this" render="#none" oncomplete="#{rich:component('confirmPanel')}.show();">
<h:graphicImage value="/images/icons/delete.gif" alt="delete" />
<a4j:param value="#{empMeet.empId}" assignTo="#{meetingBean.deleteEmpId}" />
</a4j:commandLink>
</rich:column>
</rich:extendedDataTable>
<a4j:jsFunction name="removeEmp" action="#{meetingBean.deleteEmployee}" render="table" execute="#this"
oncomplete="#{rich:component('confirmPanel')}.hide();" >
</a4j:jsFunction>
<rich:popupPanel id="statPane" autosized="true">
<h:graphicImage value="/images/ai.gif" />
Please wait...
</rich:popupPanel>
<rich:popupPanel id="confirmPanel" autosized="true" >
Are you sure you want to delete the row?
<a4j:commandButton value="Cancel" onclick="#{rich:component('confirmPane')}.hide(); return false;" />
<a4j:commandButton value="Delete" onclick="removeEmp(); return false;" />
</rich:popupPanel>
<h:commandButton action="addEmpMeeting" value="Invite More Employees" />
</h:form>
</ui:define>
</ui:composition>
</html>
Following is my bean class:
package com.drishti.apps.mommanager.meeting;
/**
* this class represents a meeting object
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.richfaces.component.SortOrder;
import com.drishti.apps.mommanager.employee.AbstractBacking;
import com.drishti.apps.mommanager.employee.EmployeeEntity;
import com.drishti.apps.mommanager.employee.EmployeeService;
#ManagedBean
public class MeetingBean extends AbstractBacking {
#ManagedProperty(value = "#{requestScope}")
private Map<String, Object> requestMap;
private int meetingId;
private Date meetingTime;
private String agenda;
private String result;
public String[] empIdsInMeeting;
private List<EmployeeEntity> employees = new ArrayList<EmployeeEntity>();
private Integer selectedMeetId;
private MeetingEntity selectedMeeting;
private String selectedAgenda;
private int deleteEmpId;
private EmployeeEntity deletableEmployee;
/**
* this method is used to load a meeting object when it is being updated
*
* #param cse
*/
public void loadMeeting(ComponentSystemEvent cse) {
if (null == getSelectedMeeting()) {
Integer meetId = getSelectedMeetId();
if (meetId == null) {
meetId = (Integer)getFlash().get("selectedMeetId");
}
if (meetId == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
MeetingEntity meet = MeetingService.getCurrentInstance().getMeetingForId(meetId);
if (meet == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
getFlash().put("selectedMeeting", meet);
getSelectedMeeting();
}
}
}
}
/**
* this method updates a meeting object
*
* #return
*/
public void updateMeeting() {
//String result = null;
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.updateMeeting(meeting);
getFlash().clear();
//result = "meetUpdated";
//return result;
}
/**
* this method adds a meeting object to database
*
* #return
*/
public void addMeeting() {
MeetingEntity meeting = (MeetingEntity)getRequestMap().get("meetingEntity");
MeetingService.getCurrentInstance().addMeeting(meeting);
//return "successMeeting";
}
/**
* this method is used to delete a meeting
*/
public void deleteMeeting(){
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.deleteMeeting(meeting);
getFlash().clear();
}
/**
* returns data model containing all meetings present in database
*
* #return
*/
public DataModel<MeetingEntity> getMeetingList() {
DataModel<MeetingEntity> meetingList = new ListDataModel<MeetingEntity>(MeetingService.getCurrentInstance()
.getMeetings());
return meetingList;
}
/**
* returns list containing agenda of all meetings
*
* #return
*/
public ArrayList<String> getAgendaList() {
ArrayList<String> agendaList = new ArrayList<String>();
agendaList.add(getSelectedMeeting().getAgenda());
return agendaList;
}
/**
* this method is used to get a list of employee names for employees who are not invited to a particular meeting
*/
public List<String> getEmpNameIdList() {
List<EmployeeEntity> employeeList = new ArrayList<EmployeeEntity>(EmployeeService.getCurrentInstance()
.getEmployeeList());
List<String> uninvitedEmpList = new ArrayList<String>();
ListIterator<EmployeeEntity> empIter = employeeList.listIterator();
ArrayList<Integer> idList = new ArrayList<Integer>();
while (empIter.hasNext()) {
idList.add(empIter.next().getEmpId());
}
MeetingEntity meeting = getSelectedMeeting();
List<EmployeeEntity> employees = meeting.getEmployees();
if(employees!=null){
ListIterator<EmployeeEntity> invitedIter = employees.listIterator();
ArrayList<Integer> invitedIds = new ArrayList<Integer>();
while (invitedIter.hasNext()) {
invitedIds.add(invitedIter.next().getEmpId());
}
idList.removeAll(invitedIds);
}
EmployeeEntity emp;
ListIterator<Integer> idIter = idList.listIterator();
while (idIter.hasNext()) {
int id = idIter.next();
emp = EmployeeService.getCurrentInstance().getEmployeeForId(id);
uninvitedEmpList.add(emp.getFirstName() + " " + emp.getLastName() + " (" + emp.getEmpId() + ")");
}
return uninvitedEmpList;
}
/**
* this method adds employees to a meeting
* #return
*/
public String addEmpToMeeting() {
MeetingEntity meeting = MeetingService.getCurrentInstance().getMeetingFromAgenda(
getSelectedMeeting().getAgenda());
for (int i = 0; i < empIdsInMeeting.length; i++) {
String id = null;
id = empIdsInMeeting[i].substring(empIdsInMeeting[i].lastIndexOf("(") + 1,
empIdsInMeeting[i].lastIndexOf(")"));
int empId = Integer.parseInt(id);
meeting.getEmployees().add(EmployeeService.getCurrentInstance().getEmployeeForId(empId));
}
MeetingService.getCurrentInstance().addMeeting(meeting);
return "empAddedToMeeting";
}
/**
* this method removes employee from a meeting
* #return
*/
public void deleteEmployee(){
List<EmployeeEntity>inviteEmployees=getSelectedMeeting().getEmployees();
EmployeeEntity emp=getDeletableEmployee();
inviteEmployees.remove(emp);
}
public Integer getSelectedMeetId() {
return selectedMeetId;
}
public void setSelectedMeetId(Integer selectedMeetId) {
this.selectedMeetId = selectedMeetId;
setSelectedMeeting(MeetingService.getCurrentInstance().getMeetingForId(selectedMeetId));
}
public MeetingEntity getSelectedMeeting() {
return selectedMeeting;
}
public void setSelectedMeeting(MeetingEntity selectedMeeting) {
this.selectedMeeting = selectedMeeting;
}
public Map<String, Object> getRequestMap() {
return requestMap;
}
public void setRequestMap(Map<String, Object> requestMap) {
this.requestMap = requestMap;
}
public Date getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(Date meetingTime) {
this.meetingTime = meetingTime;
}
public String getAgenda() {
return agenda;
}
public void setAgenda(String agenda) {
this.agenda = agenda;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public int getMeetingId() {
return this.meetingId;
}
public List<EmployeeEntity> getEmployees() {
return employees;
}
public String[] getEmpIdsInMeeting() {
return empIdsInMeeting;
}
public void setEmpIdsInMeeting(String[] empIdsInMeeting) {
this.empIdsInMeeting = empIdsInMeeting;
}
public void setEmployees(List<EmployeeEntity> employees) {
this.employees = employees;
}
public String getSelectedAgenda() {
return selectedAgenda;
}
public void setSelectedAgenda(String selectedAgenda) {
this.selectedAgenda = selectedAgenda;
}
public void setTimeOrder(SortOrder timeOrder) {
this.timeOrder = timeOrder;
}
public int getDeleteEmpId() {
return deleteEmpId;
}
public void setDeleteEmpId(int deleteEmpId) {
this.deleteEmpId = deleteEmpId;
setDeletableEmployee(EmployeeService.getCurrentInstance().getEmployeeForId(deleteEmpId));
}
public EmployeeEntity getDeletableEmployee() {
return deletableEmployee;
}
public void setDeletableEmployee(EmployeeEntity deletableEmployee) {
this.deletableEmployee = deletableEmployee;
}
}
Please help .
The problem is probably related to JSF overriding your custom onclick.
The work-around would be to use onmousedown instead of onclick, with the potential caveat described here:
http://blogs.oracle.com/jtb/entry/jsf_h_commandlink_and_onclick
i had the same problem few days ago, changing the return to true may work for you.

Resources