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 ....
Related
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() {
}
}
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.
i have one datatable with multiple selection (checkboxes). Every time this checkboxes are marked, are executed the select of the datatable again.
XHTML:
<p:dataTable id="dtUsuarios"
widgetVar="usuarios" value="#{configGruposUsuariosMB.usuarios}"
var="usuario" paginator="true" rows="10"
paginatorPosition="bottom" scrollable="true" scrollHeight="82%"
rowsPerPageTemplate="5,10,15,30,50,100"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
emptyMessage="#{i18n.datatableVazia}" lazy="true"
currentPageReportTemplate="{currentPage}/{totalPages} #{i18n.paginas} - {startRecord} #{i18n.a} {endRecord} #{i18n.de} {totalRecords}"
filteredValue="#{configGruposUsuariosMB.usuarioFiltered}"
resizableColumns="true" rowIndexVar="rowIx"
selection="#{configGruposUsuariosMB.usuariosSelecionados}"
rowKey="#{usuario.id}" style="float: right; width: 99%; overflow: hidden;" >
<p:ajax event="rowSelectCheckbox" />
<p:ajax event="rowUnselectCheckbox"/>
<f:facet name="header">
<p:outputLabel value="#{i18n.usuarios}" style="float: left;" />
</f:facet>
<f:facet name="header">
<p:outputPanel>
<h:outputText value="#{i18n.pesquisaGlobal}:" />
<p:inputText id="globalFilter" onkeyup="usuarios.filter()"
style="width:70px" />
<p:watermark value="#{i18n.filtroGlobal}" for="globalFilter" />
</p:outputPanel>
</f:facet>
<p:column id="cbx" selectionMode="multiple" style="width:17px" />
<p:column id="nome" headerText="#{i18n.nomeCompleto}"
sortBy="#{usuario.nome}" style="width:35%;">
<h:outputText value="#{usuario.nome}" />
</p:column>
<p:column id="email" headerText="#{i18n.email}"
sortBy="#{usuario.email}" style="width:35%;">
<h:outputText value="#{usuario.email}" />
</p:column>
<p:column id="grupoAtual" headerText="#{i18n.grupoAtual}"
sortBy="#{usuario.grupoUsuario.descricao}" style="width:30%;">
<h:outputText value="#{usuario.grupoUsuario.descricao}" />
</p:column>
</p:dataTable>
MB (#ViewScoped):
#ManagedBean(name = "configGruposUsuariosMB")
#ViewScoped
public class ConfigGruposUsuariosMB {
#EJB
private GrupoUsuarioService grupoUsuarioservice;
#EJB
private UsuarioService usuarioService;
#Inject
private MessagesController messages;
private GrupoUsuario grupoUsuarioSelecionado;
private List<GrupoUsuario> gruposUsuarios;
private LazyDataModel<Usuario> usuarios;
private LazyDataModel<Usuario> usuariosGrupo;
private Usuario usuarioFiltered;
private Usuario usuarioGrupoFiltered;
private List<Usuario> usuariosSelecionados;
private List<Usuario> usuariosGrupoSelecionados;
private ETipoUsuario tipoUsuarioSelecionado;
// Buscar palavras da base de internacionalizaĆ§Ć£o
ResourceBundle i18n = ResourceBundle.getBundle("br.com.sales.messages.msg",
FacesContext.getCurrentInstance().getViewRoot().getLocale());
public GrupoUsuario getGrupoUsuarioSelecionado() {
return grupoUsuarioSelecionado;
}
public void setGrupoUsuarioSelecionado(GrupoUsuario grupoUsuarioSelecionado) {
this.grupoUsuarioSelecionado = grupoUsuarioSelecionado;
}
public List<GrupoUsuario> getGruposUsuarios() {
return gruposUsuarios;
}
public void setGruposUsuarios(List<GrupoUsuario> gruposUsuarios) {
this.gruposUsuarios = gruposUsuarios;
}
public LazyDataModel<Usuario> getUsuarios() {
if (usuarios == null) {
usuarios = new GenericLazyDataModel<Usuario>(
usuarioService.findAll());
}
return usuarios;
}
public void setUsuarios(LazyDataModel<Usuario> usuarios) {
this.usuarios = usuarios;
}
public ETipoUsuario getTipoUsuarioSelecionado() {
if (tipoUsuarioSelecionado == null)
tipoUsuarioSelecionado = ETipoUsuario.A;
if (gruposUsuarios == null || gruposUsuarios.isEmpty())
carregarListaGrupos(tipoUsuarioSelecionado);
return tipoUsuarioSelecionado;
}
public void setTipoUsuarioSelecionado(ETipoUsuario tipoUsuarioSelecionado) {
this.tipoUsuarioSelecionado = tipoUsuarioSelecionado;
carregarListaGrupos(tipoUsuarioSelecionado);
}
public List<SelectItem> getTiposUsuarios() {
List<SelectItem> tipos = new ArrayList<SelectItem>();
for (ETipoUsuario tipoUsuario : ETipoUsuario.getAll()) {
tipos.add(new SelectItem(tipoUsuario, i18n.getString(tipoUsuario
.getTipo())));
}
return tipos;
}
public void carregarListaGrupos(ETipoUsuario tipo) {
gruposUsuarios = grupoUsuarioservice
.findByTipoUsuario(tipoUsuarioSelecionado);
grupoUsuarioSelecionado = getGrupoUsuarioPadrao();
}
public GrupoUsuario getGrupoUsuarioPadrao() {
for (GrupoUsuario grupo : gruposUsuarios) {
if (grupo.isPadrao())
return grupo;
}
return new GrupoUsuario();
}
public LazyDataModel<Usuario> getUsuariosGrupo() {
List<Usuario> users = usuarioService
.findByGrupoUsuario((grupoUsuarioSelecionado != null ? grupoUsuarioSelecionado
: new GrupoUsuario()));
usuariosGrupo = new GenericLazyDataModel<Usuario>(users);
return usuariosGrupo;
}
public void setUsuariosGrupo(LazyDataModel<Usuario> usuariosGrupo) {
this.usuariosGrupo = usuariosGrupo;
}
public Usuario getUsuarioFiltered() {
return usuarioFiltered;
}
public void setUsuarioFiltered(Usuario usuarioFiltered) {
this.usuarioFiltered = usuarioFiltered;
}
public Usuario getUsuarioGrupoFiltered() {
return usuarioGrupoFiltered;
}
public void setUsuarioGrupoFiltered(Usuario usuarioGrupoFiltered) {
this.usuarioGrupoFiltered = usuarioGrupoFiltered;
}
public List<Usuario> getUsuariosGrupoSelecionados() {
return usuariosGrupoSelecionados;
}
public void setUsuariosGrupoSelecionados(
List<Usuario> usuariosGrupoSelecionados) {
this.usuariosGrupoSelecionados = usuariosGrupoSelecionados;
}
public List<Usuario> getUsuariosSelecionados() {
return usuariosSelecionados;
}
public void setUsuariosSelecionados(List<Usuario> usuariosSelecionados) {
this.usuariosSelecionados = usuariosSelecionados;
}
public void reset() {
usuariosSelecionados = null;
usuariosGrupoSelecionados = null;
usuarios = null;
getUsuarios();
usuariosGrupo = null;
getUsuariosGrupo();
}
public void adicionarUsuarios() {
List<Usuario> usersAtuais = ((GenericLazyDataModel<Usuario>) usuariosGrupo)
.getDatasource();
for (Usuario user : usuariosSelecionados) {
if (!user.getGrupoUsuario().equals(grupoUsuarioSelecionado)) {
user.setGrupoUsuario(grupoUsuarioSelecionado);
usersAtuais.add(user);
}
}
// teste...
usuarioService.merge(usuariosSelecionados);
// reset();
if (usuariosSelecionados != null)
usuariosSelecionados.clear();
if (usuariosGrupoSelecionados != null)
usuariosGrupoSelecionados.clear();
usuariosGrupo = null;
usuariosGrupo = new GenericLazyDataModel<Usuario>(usersAtuais);
messages.addInfo("msgSucessoParcial");
}
public void removerUsuarios() {
boolean error = false;
for (Usuario user : usuariosGrupoSelecionados) {
if (user.getGrupoUsuario().equals(usuariosGrupoSelecionados)) {
error = true;
continue;
} else {
user.setGrupoUsuario(getGrupoUsuarioPadrao());
}
}
reset();
if (error)
messages.addWarn("msgAvisoUsuarioGrupo");
messages.addInfo("msgSucessoParcial");
}
public void save() {
usuarioService.merge(usuariosSelecionados);
messages.addInfo("msgSucesso");
}
}
If i remove the <p:ajax event="rowSelectCheckbox" /> or change to <p:ajax event="rowSelectCheckbox" process="#none"/>, the method "setUsuariosSelecionados(List usuariosSelecionados)" is not invoked.
I Just need call the "setUsuariosSelecionados(List usuariosSelecionados)" when a checkbox are marked.
I'm using JSF2, Primefaces 3.5
Sorry about my english (googleTranslate =D)
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;
}
}
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