I am developing a project using JSF. In an opening popup window, i want to show some details about a product but can not get view scoped bean' s value on a datatable.
Can you help me?
Thanks.
Here is my UrunuDenetlemeSayfasi.xhtml code snippet:
<h:commandLink onclick="window.open('UruneGozAt.xhtml',
'Ürün İçeriği', config='width=700, height=400, top=100, left=100,
scrollbars=no, resizable=no');"
action="#{uruneGozAtBean.urunIdsineGoreUrunIcerigiGetir}" value="Ürün İçeriğine Göz At">
<f:param name="urunid" value="#{urun.urunID}" />
</h:commandLink>
Here is UrunuGozAt.xhtml:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:body>
<h:dataTable class="table table-striped"
value="#{uruneGozAtBean.urunIcerik}" var="urun">
<h:column>
<f:facet name="header">
<h:outputText value="barkod no" />
</f:facet>
<h:outputText value="#{urun.barkodNo}" />
</h:column>
</h:dataTable>
</h:body>
</html>
Here is UruneGozAtBean.java
UrunDenetlemeSayfasiBean urunDenetle = new UrunDenetlemeSayfasiBean();
UrunDenetleService urunService = new UrunDenetleService();
private UrunIcerik urunIcerik = new UrunIcerik();
private Long urunIdParametre;
public UrunIcerik getUrunIcerik() {
return urunIcerik;
}
public void setUrunIcerik(UrunIcerik urunIcerik) {
this.urunIcerik = urunIcerik;
}
public Long getUrunIdParametre() {
return urunIdParametre;
}
public void setUrunIdParametre(Long urunIdParametre) {
this.urunIdParametre = urunIdParametre;
}
public void urunIdsineGoreUrunIcerigiGetir() {
setUrunIcerik(urunService.urunIdsineGoreUrunIcerigiGetir(urunIdEldeEt()));
}
public Long urunIdEldeEt(){
FacesContext fc = FacesContext.getCurrentInstance();
setUrunIdParametre(getUrunIdParametre(fc));
return getUrunIdParametre();
}
public Long getUrunIdParametre(FacesContext fc){
Map<String, String> parametre = fc.getExternalContext().getRequestParameterMap();
return Long.valueOf(parametre.get("urunid")).longValue();
}
EDIT:
This is now my current implementation, it returns null.
i am developing a project using JSF. In an opening popup window, i want to show some details about a product but can not get view scoped bean' s value on a datatable.
Can you help me?
Thanks.
Here is my UrunuDenetlemeSayfasi.xhtml code snippet:
<h:commandLink onclick="window.open('UruneGozAt.xhtml','Ürün İçeriği',
config='width=700, height=400, top=100, left=100, scrollbars=no, resizable=no');"
value="Ürün İçeriğine Göz At"> <f:param name="urunId" value="#{urun.urunID}" />
</h:commandLink>
Here is UruneGozAt.xhtml:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<f:metadata>
<f:viewParam name="urunId" value="#{uruneGozAtBean.urunId}"
required="false" />
<f:viewAction action="#{uruneGozAtBean.urunIdsineGoreUrunIcerigiGetir()}" />
</f:metadata>
<h:head>
<title>Ürün İçeriği</title>
<!-- add this always, even if it's empty -->
</h:head>
<h:body>
<h:dataTable class="table table-striped"
value="#{uruneGozAtBean.urunIcerik}" var="urun">
<h:column>
<f:facet name="header">
<h:outputText value="barkod no" />
</f:facet>
<h:outputText value="#{urun.barkodNo}" />
</h:column>
</h:dataTable>
</h:body>
</html>
Here is UruneGozAtBean.java
#ManagedBean
#ViewScoped
public class UruneGozAtBean {
public UrunDenetlemeSayfasiBean urunDenetle = new UrunDenetlemeSayfasiBean();
public UrunDenetleService urunService = new UrunDenetleService();
private ArrayList<UrunIcerik> urunIcerik = new ArrayList<UrunIcerik>();
private Long urunId;
public Long getUrunId() {
return urunId;
}
public void setUrunId(Long urunId) {
this.urunId = urunId;
}
public ArrayList<UrunIcerik> getUrunIcerik() {
return urunIcerik;
}
public void setUrunIcerik(ArrayList<UrunIcerik> urunIcerik) {
this.urunIcerik = urunIcerik;
}
public void urunIdsineGoreUrunIcerigiGetir() {
setUrunIcerik(urunService.urunIdsineGoreUrunIcerigiGetir(urunIdEldeEt()));
System.out.print("aaa");
}
public Long urunIdEldeEt() {
FacesContext fc = FacesContext.getCurrentInstance();
setUrunId(getUrunId(fc));
return getUrunId();
}
public Long getUrunId(FacesContext fc) {
Map<String, String> parametre = fc.getExternalContext().getRequestParameterMap();
return Long.valueOf(parametre.get("urunId")).longValue();
}
}
#ViewScoped beans are alive per view. If you open a popup window from your current view, then you're opening a new view, so even if it uses the same managed bean to display the data, since they're different views, they use different instances of the same class.
In cases like this, you should pass a parameter through query string, then receive it in your view and process it to load the desired data. In this case, your code would be like this (note: make sure you send the parameter with name "urunId"):
UrunuGozAt.xhtml:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<!-- add this always, even if it's empty -->
<f:metadata>
<f:viewParam name="urunId" value="#{uruneGozAtBean.urunId}"
required="false" />
<f:viewAction action="#{uruneGozAtBean.loadData}" />
</f:metadata>
</h:head>
<h:body>
<h:dataTable class="table table-striped"
value="#{uruneGozAtBean.urunIcerik}" var="urun">
<h:column>
<f:facet name="header">
<h:outputText value="barkod no" />
</f:facet>
<h:outputText value="#{urun.barkodNo}" />
</h:column>
</h:dataTable>
</h:body>
</html>
UruneGozAtBean managed bean:
#ViewScoped
#ManagedBean
public class UruneGozAtBean {
//your current fields, getters and setters...
private Long urunId;
//getter and setter for this field...
public void loadData() {
if (urunId != null) {
//load the data for the table...
}
}
}
More info:
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
How to choose the right bean scope?
DataTable expects a list to iterate through, but as far as I can see you return an UrunIcerik object.
Related
I've one table embedded into another table. My problem: How to render only the inner table when a row was removed?
Bean:
#Named
#ViewScoped
public class TestBean implements Serializable {
private static final long serialVersionUID = -5633666299306108430L;
private List<String> strLst1;
private List<String> strLst2;
#PostConstruct
public void init() {
strLst1 = Arrays.asList("a", "b", "c");
strLst2 = Arrays.asList("d", "e", "f");
}
public List<String> getStrLst1() {
return strLst1;
}
public List<String> getStrLst2() {
return strLst2;
}
public void removeFromStrLst2(String val) {
strLst2.remove(val);
}
}
Facelet:
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
</h:head>
<h:body>
<h:form id="form">
<h:dataTable
id="outerTable"
var="str1"
value="#{testBean.strLst1}"
border="1">
<h:column>
<h:panelGroup id="innerTableContainer">
<h:dataTable
id="innerTable"
var="str2"
value="#{testBean.strLst2}"
border="1">
<h:column>
<h:outputText value="#{str1}: #{str2}" />
</h:column>
<h:column>
<h:commandButton
id="removeButton"
action="#{testBean.removeFromStrLst2(str2)}"
value="RemoveFromStrLst2">
<f:ajax render="innerTableContainer" /> <!-- Problem location -->
</h:commandButton>
</h:column>
</h:dataTable>
</h:panelGroup>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
My problem is the Ajax-render attribute which doesn't get the correct id (examples for the first row):
innerTableContainer leads to mojarra.ab(this,event,'action',0,'innerTableContainer') It doesn't work!
innerTable leads to mojarra.ab(this,event,'action',0,'form:outerTable:0:innerTable:0') It doesn't work!
#parent leads to mojarra.ab(this,event,'action',0,'form:outerTable:0:innerTable:0:j_idt14') It doesn't work!
#namingcontainer leads to mojarra.ab(this,event,'action',0,'form:outerTable:0:innerTable:0') It doesn't work!
#form works but this isn't I was looking for.
The correct and working id would be form:outerTable:0:innerTableContainer but how to get it?
Mojarra 2.3.9.SP01
I thought I'd try and get a primefaces datagrid working with my JSF code, but I always got "no results found". So I'm trying to set up a simple example but I get the same error messages so I must be doing something fundamentally wrong.
I have the following backing bean:
#ManagedBean
#ViewScoped
public class CarBean {
private static final Logger logger = Logger.getLogger("datagrid.ejb.CarBean");
private List<Car> cars;
public CarBean() {
cars = new ArrayList<Car>();
cars.add(new Car("myModel",2005,"ManufacturerX","blue"));
logger.log(LogLevel.INFO, "added car");
//add more cars
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}
And the following xhtml page:
<!DOCTYPE html>
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<p:dataGrid var="car" value="#{carBean.cars}" columns="3"
rows="12"layout="grid">
<p:column>
<p:panel header="#{car.model}">
<h:panelGrid columns="1">
<p:graphicImage value="/images/cars/#{car.manufacturer}.jpg"/>
<h:outputText value="#{car.year}" />
</h:panelGrid>
</p:panel>
</p:column>
</p:dataGrid>
</h:body>
</html>
I can see from the logs and debugger that the CarBean is instantiated but still I get the no records found error. Any ideas?
Thanks,
Zobbo
I'm using prime-faces Tabs to display multiple input forms. The problem is, there are times when I need to instantiate 2 of the same form. They both of course use the same Managed Bean which causes the input of the first initialized form to override the other with the same data. I need to be able to put different data in each form and submit both of them collectively. Each form goes into a list and forwarded on for calculation. I've been reading scope scope scope scope but the only scope that works somewhat is "Sessioned". Session only allows one instance of the Managed Bean and places the form data into the list, "Request, View scope" Doesn't place the data into the list respectively nor does it hold the data. The Managed Bean is serializable and in sessioned scope. I've read the other post and they don't work. Any ideas?
Backing Bean
#ManagedBean
#SessionScoped
public class RequestCalculation {
private CalculationRequest calcReq;
private List<ViewTabs> formTabs;
private String id;
private boolean calcButton;
public RequestCalculation() {
calcReq = new CalculationRequest();
formTabs = new ArrayList<ViewTabs>();
calcButton = false;
}
public String loadForm(TcsBase loadForm) {
id = loadForm.getId();
ViewTabs tab = new ViewTabs();
tab.setFormTitle("Form".concat(id));
tab.setFormPage("Form".concat(id).concat(".xhtml"));
formTabs.add(0, tab);
calcReq.getFormCollection().add(0, loadForm);
loadCalcButton();
return "Main";
}
public void loadCalcButton() {
if (formTabs.isEmpty())
isCalcButton();
else {
calcButton = true;
}
}
public void onTabClosed(TabCloseEvent e) {
TabView tabView = (TabView) e.getComponent();
int closingTabIndex = tabView.getChildren().indexOf(e.getTab());
removeForm(closingTabIndex);
formTabs.remove(closingTabIndex);
loadCalcButton();
}
public void removeForm(int index) {
TcsBase formIndex = calcReq.getFormCollection().get(index);
String formId = formIndex.getId();
// Creates a new instance of the selected form
FacesContext fc = FacesContext.getCurrentInstance();
fc.getELContext().getELResolver()
.setValue(fc.getELContext(), null, "form".concat(formId), null);
calcReq.getFormCollection().remove(index);
formTabs.remove(index);
}
public String calculate() {
CalculateService service = new CalculateService();
CalculatorInterface calculateInterface = service.getCalculatePort();
XStream xstream = new XStream(new StaxDriver());
xstream.registerConverter(new JodaTimeConverter());
// Here is where the client request (input) is converted to an Xml
// string before going
// to the Web Service
String xml = xstream.toXML(calcReq);
String request = calculateInterface.calculate(xml);
// Here the response back from the Web Service is converted back from
// Xml to a string
// to be displayed to the user in Xhtml
calcReq = (CalculationRequest) xstream.fromXML(request);
FacesContext fc = FacesContext.getCurrentInstance();
for (int i = 0; i < calcReq.getFormCollection().size(); i++) {
TcsBase newFrm = calcReq.getFormCollection().get(i);
String frmId = newFrm.getId();
fc.getELContext()
.getELResolver()
.setValue(fc.getELContext(), null, "form".concat(frmId),
newFrm);
}
return null;
}
public List<ViewTabs> getFormTabs() {
return formTabs;
}
public void setFormTabs(List<ViewTabs> formTabs) {
this.formTabs = formTabs;
}
public boolean isCalcButton() {
return calcButton;
}
public void setCalcButton(boolean calcButton) {
this.calcButton = calcButton;
}
}
**Html Menu **
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<head>
</head>
<f:view>
<h:body>
<h:commandLink action="#{requestCalculation.loadForm(formA)}" value="FormA" /> <br/>
<h:commandLink action="#{requestCalculation.loadForm(formB)}" value="FormB" /> <br/><br/><br/>
</h:body>
</f:view>
</html>
Html Main page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<f:view>
<h:head>
<title> TCS </title>
</h:head>
<h:form >
<p:layout style="min-width:400px;min-height:700px " >
<p:layoutUnit position="north" style="text-align:center">
<p style="text-align:center; font-size:28px">Tax Computation Service</p>
</p:layoutUnit>
<p:layoutUnit header="Menu" position="west" style="min-width:190px; min-height:50px; ">
<p:panelMenu>
<p:submenu label="Forms">
<p:submenu label="Individual Forms">
<p:menuitem>
<ui:include src="Menu.xhtml" />
</p:menuitem>
</p:submenu>
</p:submenu>
</p:panelMenu>
</p:layoutUnit>
<p:layoutUnit position="center" >
<p:tabView onTabShow="focus" widgetVar="tabView">
<p:ajax event="tabClose" listener="#{requestCalculation.onTabClosed}"/>
<c:forEach items="#{requestCalculation.formTabs}" var="listItem">
<p:tab title="#{listItem.formTitle}" closable="true" >
<ui:include src="#{listItem.formPage}" />
</p:tab>
</c:forEach>
</p:tabView>
<p:panelGrid columns="0" >
<p:commandButton value="Calculate" action = "#{requestCalculation.calculate}" ajax="false" rendered="#{requestCalculation.calcButton}" />
</p:panelGrid>
</p:layoutUnit>
</p:layout>
</h:form>
</f:view>
</html>
FormA Html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<f:view>
<h:head>
<title> FormA</title>
</h:head>
<h:body>
<p:focus />
<p:panelGrid id="panelGridA" columns="2">
<p:outputLabel value="Form ID: " style="width: 725px" />
<p:outputLabel value="#{formA.id}" />
<p:outputLabel value="4. . . " style="width: 725px" />
<p:inputText id="input1" style="text-align:right" value="#{formA.line4}" converter="bdNullableConverter" onfocus="this.select()"/>
<p:outputLabel value="5. . . . . . . " style="width: 725px" />
<p:inputText style="text-align:right" value="#{formA.line5}" converter="bdNullableConverter" onfocus="this.select()" />
<p:outputLabel value="6. . . . . . . . " style="width: 725px" />
<p:outputLabel value="#{formA.line6}" converter="bdNullableConverter" />
</p:panelGrid>
</h:body>
</f:view>
</html>
Instead of trying to use multiple instances of a managed bean, use ONE managed bean that gives access to multiple instances of a class via e.g. a hashmap or arraylist or whatever you want to use. Just like you would in plain old java programming. You cannot have two variables with the same name:
#ViewScoped
#Named
public class RequestCalculations {
Map<String, RequestCalculation> hm;
#PostConstruct
public init() {
hm = new HashMap<>();
// prepopulate if known upfront
hm.put("1", new RequestCalculation());
hm.put("2", new RequestCalculation());
}
public HashMap<String, RequestCalculation> getCalculations() {
return hm;
}
}
Then use the tabIndex of the tab as the key to the hashmap (or an array list). And in your xhtml do something like
#{requestCalculations.calculations[myTabIndex]}
You might need to pass this on to the include via a include param if you need this IN the include (as I think you do)
If you want to use the multiple instances of manager bean, then you can declare it in faces-config.xml file with different names and use it independently. See example
<managed-bean>
<managed-bean-name>productSearchForm</managed-bean-name>
<managed-bean-class>com.company.package.ProductSearchForm</managed-bean-class>
<managed-bean-scope>view</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>productChildFilter</managed-bean-name>
<managed-bean-class>com.company.package.ProductSearchForm</managed-bean-class>
<managed-bean-scope>view</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>productAttachFilter</managed-bean-name>
<managed-bean-class>com.company.package.ProductSearchForm</managed-bean-class>
<managed-bean-scope>view</managed-bean-scope>
</managed-bean>
Edit for JSF 2.3:
If you are using CDI, then you can inject files with different names
#Inject
#ManagedProperty(value = "#{productSearchForm}")
private ProductSearchForm productSearchForm;
#Inject
#ManagedProperty(value = "#{productCandidateForm}")
private ProductSearchForm productCandidateForm;
With primefaces I made a multicheckbox with several divisions to choose. After clicking the submit Button the chosen divisions should be listed in a datatable with the associated items in a subtable. There could be 0 - n items which should be shown in the subtable.
division1 -> item1, item2
division2 -> item3, item4, item5
The first impression of the webpage looks fine. When I only choose one division and press submit the fitting items will be shown. But when I want to display other items they get overwritten. e.g. when I choose division2 it will display the items item1, item2 and item 5.
How can I make it so that the items will be loaded correctly every time?
I also changed the subtable to a nested datatable, but the behaviour was the same.
I've primefaces version 4.0
Below is my code:
division_list.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Gruppenverwaltung</title>
</h:head>
<h:body>
<f:view>
<h:form id="myForm">
<h2>
<h:outputText value="Division List" />
</h2>
<h:outputText value="Grid: " />
<p:selectOneRadio id="grid" value="#{divisionController.selectedDivisions}" layout="grid" columns="3"
converter="DivisionConverter">
<f:selectItems value="#{divisionController.divisions}" />
</p:selectOneRadio>
<p:commandButton value="Submit" update=":myForm" />
<p:dataTable id="dtDivisions" value="#{divisionController.selectedDivisions}" var="division">
<p:subTable id="stItems" var="item" value="#{division.items}">><f:facet name="header">
<h:outputText value="#{division.name}" />
</f:facet>
<p:column>
<h:inputText value="#{item.name}" />
</p:column>
<p:column>
<p:commandButton icon="ui-icon-disk" action="#{divisionController.doUpdateItem(item)}" />
<p:commandButton icon="ui-icon-trash" oncomplete="confirm.show()">
<f:setPropertyActionListener target="#{divisionController.selectedItem}" value="#{item}" />
</p:commandButton>
</p:column>
</p:subTable>
</p:dataTable>
</h:form>
<p:confirmDialog message="Gewählter Eintrag löschen?" widgetVar="confirm"> --><h:form
id="formDialog">
<p:commandButton value="Yes" action="#{divisionController.doDeleteItem}"
styleClass="ui-confirmdialog-yes" icon="ui-icon-check" oncomplete="confirmation.hide()" />
<p:commandButton value="No" type="button" onclick="confirm.hide()" styleClass="ui-confirmdialog-no"
icon="ui-icon-close" />
</h:form>
</p:confirmDialog>
</f:view>
</h:body>
</html>
DivisonController.java:
...
#ManagedBean
#ViewScoped
public class DivisionController implements Serializable {
...
private List<DivisionDto> divisions;
private List<DivisionDto> selectedDivisions;
...
#PostConstruct
public void init() throws MappingTOException {
....
if (divisions == null) {
divisions = club.getDivisions();
}
}
...
DivisionDto.java
...
public class DivisionDto {
....
private List<ItemDto> items;
private String name;
...
ItemDto.java
...
public class ItemDto {
...
private DivisionDto division;
private String name;
...
DivisionConverter.java
#FacesConverter(value = "DivisionConverter")
public class DivisionConverter implements Converter {
private static Map<String, DivisionDto> divisionCache = new HashMap<String, DivisionDto>();
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
DivisionDto val = divisionCache.get(value);
if (val == null) {
val = new DivisionDto();
val.setName(value);
}
return val;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value instanceof DivisionDto) {
DivisionDto division = (DivisionDto) value;
divisionCache.put(division.getName(), division);
return division.getName();
} else {
return "";
}
}
}
I would be really grateful for any help.
I solved the issue wie a datatable in a datatable and put a filter on the first datatable. Now it works as expected.
I am not able to get he the selected value from the table withe bean in View scope.
Following code doesn't work but it works when I uses Session or Request scope.
Here's my JSF page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<f:view>
<h:head>
<title>Sample JSF/Prime Page</title>
</h:head>
<h:body>
<h:form id="primeForm">
<p:panel id="toggle1" header="Panel 1" collapsed="#{prime.toggle1}" footer=" footer Info if required " toggleable="true" closable="true" >
<p:dataTable id="cars" value="#{prime.listModel}" var="data" paginator="true" style="width:500px"
selection="#{prime.selected}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{prime.onRowSelect}" />
<f:facet name="header">
Select a row to display a message
</f:facet>
<p:column headerText="Model">
#{data.number}
</p:column>
<p:column headerText="Model">
#{data.number}
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</h:body>
</f:view>
</html>
Here's my bean:
#ManagedBean
#ViewScoped
public class Prime implements Serializable {
ArrayList<UIData> list = new ArrayList<UIData>();
private UIData selected;
private UIDataModel listModel;
private String testVaue;
private ArrayList<String> tmp = new ArrayList<String>();
private HashMap<String, List<String>> pagesMap = new HashMap<String, List<String>>();
private boolean toggle1 = true;
public Prime() {
for (int k = 1; k < 3; k++) {
UIData model =new UIData(""+k, ""+k);
list.add(model);
}
listModel = new UIDataModel(list);
}
public void onRowSelect(SelectEvent event) {
try{
System.out.println("Sellected Value : "+((UIData)event.getObject()).getNumber());
}catch (Exception e) {
e.printStackTrace();
}
}
// Getters and setters.
}
Add proper rowKey attribute to datatable. Primefaces must have a way to uniquely identify you row. That's why you should set a property which is unique to you dataset. Usually this is database primary key. In your case for example it coul be rowKey=#{data.number}.