How to pass selected row data from datatable between two beans [duplicate] - jsf

This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 6 years ago.
I've got a datatable with values in which I get from my DB.
In my class myBean, I've got an Variable of type User to store the selected row. It just can be selected one row. Now I want to call this Variable from an other bean which is called printUser to get the selected User.
But it always prints null.
View
<p:dataTable id="userDT" var="user" value="#{myBean.getUserList()}" selection="#{myBean.selectedUser}"
rowKey="#{user.id}" >
<p:column selectionMode="single" style="width:16px;text-align:center"/>
<p:column width="200" headerText="ID">
<h:outputText value="#{user.id}" />
</p:column>
<p:column width="200" headerText="Firstname">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column width="250" headerText="Lastname">
<h:outputText value="#{user.lastname}" />
</p:column>
</p:dataTable>
myBean
#Named(value = "myBean")
#ManagedBean
#SessionScoped
public class myBean implements Serializable {
private static final long serialVersionUID = 1L;
private User selectedUser = new User();
public myBean() {
}
public List<User> getUserList() {
...
}
public Patient getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser= selectedUser;
}
}
User.java
public class User {
private Integer id;
private String firstname;
private String lastname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
printUser
#Named(value = "printUser")
#ManagedBean
#RequestScoped
public class printUser {
public printUser() {
}
public void getSelectedUserData(){
myBean bean = new myBean();
User user = new User();
user = bean.getSelectedUser();
System.err.println("UserID: " + user.getID());
}
}
Hope you undertand my Problem.
Thanks alot
Excuse my English

This is an example to use the entity of the selected row in the same page and in another page. The example use Lombok Getter,Setter and Data annotations for shortness:
The entity for the DataTable:
#Entity
#Data
#TableGenerator( name = "GEN_TestEntity1", table = "ID_Generator", pkColumnName = "GEN_KEY", pkColumnValue = "GEN_TestEntity1", valueColumnName = "GEN_VALUE" )
#NamedQuery( name = TestEntity1.QUERY_ALL_TESTENTITY1, query = "SELECT te1 FROM TestEntity1 te1" )
public class TestEntity1 implements Serializable
{
public static final String QUERY_ALL_TESTENTITY1 = "query_All_TestEntity1";
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.TABLE, generator = "GEN_TestEntity1" )
private int id;
#Column
private String name;
}
The ManagedBean as a controller:
#ManagedBean
#SessionScoped
public class EntityBean
{
#EJB
private EntitySER entitySER;
#Getter
#Setter
private TestEntity1 selectedEntity;
public List<TestEntity1> getAllTestEntity1()
{
return entitySER.getAllTestEntity1();
}
public void onRowSelect( SelectEvent event_ )
{
}
}
Another ManagedBean which uses the first one (if you really want it):
#ManagedBean
#RequestScoped
public class AnotherBean
{
#ManagedProperty( value="#{entityBean}" )
private EntityBean entityBean;
...
}
The stateless session bean:
#Stateless
#LocalBean
public class EntitySER
{
#PersistenceContext
private EntityManager em;
public List<TestEntity1> getAllTestEntity1()
{
Query q = em.createNamedQuery( TestEntity1.QUERY_ALL_TESTENTITY1 );
return q.getResultList();
}
}
The index page (index.xhtml):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Page 1</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable id="table_TestEntity1" value="#{entityBean.allTestEntity1}" var="entity" selection="#{entityBean.selectedEntity}"
rowKey="#{entity.id}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{entityBean.onRowSelect}" update=":form:entID :form:entName"/>
<p:column>
#{entity.id}
</p:column>
<p:column>
#{entity.name}
</p:column>
</p:dataTable>
<p>
<h:outputLabel id="entID" value="#{entityBean.selectedEntity.id}"/>:
<h:outputLabel id="entName" value="#{entityBean.selectedEntity.name}"/>
</p>
<p>
<h:commandButton value="Page 2" action="/faces/another.xhtml"/>
</p>
</h:form>
</h:body>
</html>
The another Page (another.xhtml):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Another Page</title>
</h:head>
<h:body>
<p>
The selected entity: #{entityBean.selectedEntity.id}:#{entityBean.selectedEntity.name}
</p>
<h:form>
<h:commandButton value="Back" action="/faces/index.xhtml"/>
</h:form>
</h:body>
</html>

Related

JSF selectOneMenu [duplicate]

This question already has answers here:
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 8 years ago.
I am new in JSF and facing problem in getting the drop down list. I don't want to use the #PostConstructor. I tried couple of sources on google but i don't know where i am making the mistake. please hep me out.
Managed Bean
package com.employee.registration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class EmployeeBean implements Serializable {
private static final long serialVersionUID = -5400118477202860998L;
private String firstName;
private String lastName;
private String emailID;
private int employeeNumber;
private String employeeDepartment;
private String dplist;
private List<DepartmentList> departmentList;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailID() {
return emailID;
}
public void setEmailID(String emailID) {
this.emailID = emailID;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeDepartment() {
return employeeDepartment;
}
public void setEmployeeDepartment(String employeeDepartment) {
this.employeeDepartment = employeeDepartment;
}
public List<DepartmentList> getDepartmentList() {
return departmentList;
}
public void setDepartmentList(List<DepartmentList> departmentList) {
this.departmentList = departmentList;
}
public List<DepartmentList> getDepartments() {
departmentList = new ArrayList<DepartmentList>();
departmentList.add(new DepartmentList("1", "Finance"));
departmentList.add(new DepartmentList("2", "Bnking"));
return departmentList;
}
public String getDplist() {
return dplist;
}
public void setDplist(String dplist) {
this.dplist = dplist;
}
}
Java Class
package com.employee.registration;
public class DepartmentList {
private String departmentId;
private String departmentName;
public DepartmentList(String departmentId, String departmentName) {
this.departmentId = departmentId;
this.departmentName = departmentName;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
XHTML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Employee Registration</title>
<h:outputStylesheet library="css" name="stylesheet.css" />
</h:head>
<h:body>
<h:form>
<fieldset>
<legend>Enter the Employees Information </legend>
<h:outputLabel id="firstName" value="First Name :" for="fName"></h:outputLabel>
<h:inputText id="fName" value="#{employeeBean.firstName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="lastName" value="Last Name :" for="lName"></h:outputLabel>
<h:inputText id="lName" value="#{employeeBean.lastName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="emailId" value="Email ID :"></h:outputLabel>
<h:inputText id="email" value="#{employeeBean.emailID}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="employeeNumberId" value="Employee Number :"></h:outputLabel>
<h:inputText id="empNumber" value="#{employeeBean.employeeNumber}"></h:inputText>
<br></br>
<h:outputLabel id="employeeDepartmentID" value="Employee Department"></h:outputLabel>
<h:inputText id="eDepartment"
value="#{employeeBean.employeeDepartment}"></h:inputText>
<br></br>
<h:selectOneMenu value="#{employeeBean.dplist}"></h:selectOneMenu>
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}"></f:selectItems>
<h:commandButton id="submit" value="Submit"
action="outputInformation"></h:commandButton>
</fieldset>
</h:form>
</h:body>
</html>
selectItems tag should be inside selectOneMenu :)
<h:selectOneMenu value="#{employeeBean.dplist}}">
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}" />
</h:selectOneMenu>
see tutorial here

PrimeFaces DataTables not working

I'm new to PrimeFaces tried out an example in PrimeFaces datatable
public class Datatable {
private String fname;
private String lname;
private int age;
public Datatable(String fname, String lname, int age) {
// TODO Auto-generated constructor stub
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Here in the class I have declared what are the fields in the data table
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean(name="solodat")
#RequestScoped
public class Solodata implements Serializable{
private static final long serialVersionUID = 1L;
public Solodata() {}
private List<Datatable>addeta;
public List<Datatable> getAddeta() {
return addeta;
}
public void setAddeta(List<Datatable> addeta) {
this.addeta = addeta;
}
#PostConstruct
public void init() {
List<Datatable> addeta=new ArrayList<Datatable>();
addeta.add( new Datatable("man","eater",14));
addeta.add( new Datatable("solo","world",28));
addeta.add( new Datatable("antan","evanious",20));
addeta.add( new Datatable("hi","daa",29));
addeta.add( new Datatable("thallu","vandi",30));
addeta.add( new Datatable("prime","faces",1000));
addeta.add( new Datatable("crime","shit",1412));
addeta.add( new Datatable("shit","head",18));
}
}
Here in list I have get that values:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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://www.java.com/jsf/html"
xmlns:f="http://www.java.com/jsf/core"
xmlns:p="http://www.primefaces.org/ui">
<h:head>
<title>DATA TABLES DEMO</title>
</h:head>
<h:body>
<h:form>
<h1>output values</h1>
<p:dataTable var="sol" value="#{solodat.addeta}" >
<p:column headerText="LASTNAME">
<h:outputText value="#{sol.lname}"/>
</p:column>
<p:column headerText="age">
<h:outputText value="#{sol.age}"/>
</p:column>
<p:column headerText="first">
<h:outputText value="#{sol.fname}"/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
This is the xhtml page to get the bean values by data table but JSF is showing an empty page. Any help would be appreciated.
Try this and let us know (using CDI, removing the useless constructor, and initializing addeta properly)
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
#Named("solodat")
#RequestScoped
public class Solodata {
private List<Datatable> addeta;
public List<Datatable> getAddeta() {
return addeta;
}
public void setAddeta(List<Datatable> addeta) {
this.addeta = addeta;
}
#PostConstruct
public void init() {
addeta=new ArrayList<Datatable>();
addeta.add( new Datatable("man","eater",14));
addeta.add( new Datatable("solo","world",28));
addeta.add( new Datatable("antan","evanious",20));
addeta.add( new Datatable("hi","daa",29));
addeta.add( new Datatable("thallu","vandi",30));
addeta.add( new Datatable("prime","faces",1000));
addeta.add( new Datatable("crime","shit",1412));
addeta.add( new Datatable("shit","head",18));
}
}
And replace the facelet with this one (I changed the first lines)
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>DATA TABLES DEMO</title>
</h:head>
<h:body>
<h:form>
<h1>output values</h1>
<p:dataTable var="sol" value="#{solodat.addeta}" >
<p:column headerText="LASTNAME">
<h:outputText value="#{sol.lname}"/>
</p:column>
<p:column headerText="age">
<h:outputText value="#{sol.age}"/>
</p:column>
<p:column headerText="first">
<h:outputText value="#{sol.fname}"/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
Now make sure you have placed Primefaces library at the right place, and that the app is being deployed on a running server without errors.
Edit: The reason you don't have data , is due to Datatable's constructor, which is incomplete.
Replace
public Datatable(String fname, String lname, int age) {
// TODO Auto-generated constructor stub
}
by
public Datatable(String fname, String lname, int age) {
this.fname = fname;
this.lname = lname;
this.age = age;
}
Small mistake: You are initializing a new local variable in init().
List<Datatable> addeta = new ArrayList<Datatable>();
Change it to:
this.addeta = new ArrayList<Datatable>();
You should use <!DOCTYPE html> instead of
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
and also change your are initializing as noone answer.
See also : Wrong doctype when one is specified in composite view

How to send values to a list in a backing bean and display as a dataTable

I'm still learning how to use Facelets and I am trying to send inputted values from a JSF page to a list in a ManagedBean and then display that information in a dataTable. I have JSF page to enter in the data, a backing bean to manage the list, and a regular application for the normal objects. I can't figure out how to send the input value from the JSF to the backing bean, however.
Here is my view:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Guestbook Form</title>
</h:head>
<h:body>
<h:form>
<h1>Guestbook Application Form</h1>
<p>Please fill out all entries and click the Submit button</p>
<h:panelGrid columns="3">
<h:outputText value = "Name: "></h:outputText>
<h:inputText id="nameInputText" required ="true"
requiredMessage="Please enter your name"
value = "#{guestbookBean.name}"
validatorMessage="Name must be fewer than 20
characters">
<f:validateLength maximum="20"/>
</h:inputText>
<h:message for="nameInputText" styleClass="error"/>
<h:outputText value = "Email: "></h:outputText>
<h:inputText id="emailInputText" required ="true"
requiredMessage="Please enter your email address"
value="#{guestbookBean.email}"
validatorMessage="Invalid email address format">
<f:validateRegex pattern ="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
</h:inputText>
<h:message for="emailInputText" styleClass="error"/>
<h:outputText value = "Enter a message: "></h:outputText>
<h:inputTextarea id="messageInputText" required ="true"
requiredMessage="Please enter a message"
value="#{guestbookBean.message}"
validatorMessage="Message must be fewer than 140 characters">
<f:validateLength maximum="140"/>
</h:inputTextarea>
<h:message for="messageInputText" styleClass="error"/>
</h:panelGrid>
<h:commandButton value="Submit" type ="Submit" action ="#{guestbookBean.setList()}"/>
<h:commandButton value ="Reset Form" type ="reset"/>
<h:outputText escape="false" value ="#{guestbookBean.result}"/>
<h:dataTable value="#{guestbookBean.list}" var="guests"
styleClass="table" cellpadding="5" cellspacing="1" border="2">
<h:column>
<f:facet name ="header">Name</f:facet>
#{guests.name}
</h:column>
<h:column>
<f:facet name ="header">Email</f:facet>
#{guests.email}
</h:column>
<h:column>
<f:facet name ="header">Message</f:facet>
#{guests.message}
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
Here is my backing bean:
package guestbook;
import java.util.List;
import java.util.ArrayList;
import java.io.Serializable;
import javax.enterprise.context.Dependent;
import javax.faces.bean.*;
#ManagedBean(name = "guestbookBean")
public class GuestbookBean implements Serializable{
private String na;
private String em;
private String m;
private List<GuestbookEntry> bookList = new ArrayList<>();
//Set name
public void setName(String first)
{
this.na = first;
}
//Set email
public void setEmail(String mail)
{
this.em = mail;
}
//Set message
public void setMessage(String msg)
{
this.m = msg;
}
//Return the name
public String getName()
{
return na;
}
//Return the email
public String getEmail()
{
return em;
}
//Return the message
public String getMessage()
{
return m;
}
public void setList()
{
GuestbookEntry bk = new GuestbookEntry();
bk.setName(na);
bk.setEmail(em);
bk.setMessage(m);
bookList.add(0, bk);
}
public List<GuestbookEntry> getList()
{
return bookList;
}
// returns result for rendering on the client
public String getResult()
{
if ( !bookList.isEmpty())
{
return "<p style=\"background-color:yellow;width:200px;" +
"padding:5px\">Data submitted successfully"+ "</p>";
}
else
{
return ""; // request has not yet been made
}
} // end method getResult
}
Here is my model:
package guestbook;
public class GuestbookEntry {
private String firstName;
private String lastName;
private String email;
private String message;
public void setFirstName(String fn)
{
firstName = fn;
}
public void setLastName(String ln)
{
lastName = ln;
}
public void setEmail(String em)
{
email = em;
}
public void setMessage(String m)
{
message = m;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getEmail()
{
return email;
}
public String getMessage()
{
return message;
}
}
The data is not being reset because you are not clearing the fields after the submit
You can set to null na, em and m to reset the fields
Regarding the table, try adding #ViewScoped to your bean, the default scope is RequestScope, which is not keeping your table

How to map an object in jsf from backing bean?

I am getting error while running this snippet as /facelet/crew/objectMapGossip.xhtml #14,94 value="#{objcetMapBean.searchCrewParam.staffNum}": Property 'staffNum' not readable on type java.lang.String
please help me out from this small error .. I am new to jsf so stucking at things basic ...
Thanks in advance :-)
This is my backing bean...
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "objcetMapBean")
public class ObjectMapGossip {
private SearchCrew1 searchCrewParam = new SearchCrew1("212","kart","asd");
public SearchCrew1 getSearchCrewParam() {
return searchCrewParam;
}
public void setSearchCrewParam(SearchCrew1 searchCrewParam) {
this.searchCrewParam = searchCrewParam;
}
public String search() {
return "success";
}
}
class SearchCrew1 {
public SearchCrew1() {
super();
}
/**
* #param staffNum
* #param surName
* #param rank
*/
public SearchCrew1(String staffNum, String surName, String rank) {
super();
this.staffNum = staffNum;
this.surName = surName;
this.rank = rank;
}
private String staffNum;
private String surName;
private String rank;
public String getStaffNum() {
return staffNum;
}
public void setStaffNum(String staffNum) {
this.staffNum = staffNum;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
}
This is my jsf page
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns: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>
<ui:composition template="/facelet/layout/mainlayout.xhtml">
<ui:define name="content">
<h:form>
<div align="left">
<h:outputText value="Staff Number: " />
<h:inputText id="staffnum" size="6" value="# {objcetMapBean.searchCrewParam.staffNum}" />
<h:outputText value="Surname: " />
<h:inputText id="surname" size="10" maxlength="25" value="# {objcetMapBean.searchCrewParam.surName}" />
<h:outputText value="Rank: " />
<h:inputText id="rank" size="3" value="#{objcetMapBean.searchCrewParam.rank}" />
<h:commandButton value="Search" action="#{objcetMapBean.search}" />
</div>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
We can use h:dataTable from jsf tag and map easily.
http://www.mkyong.com/jsf2/jsf-2-datatable-example/

Primefaces Datatable Selection Object

I have a question to the Primefaces Datatable, especially to the Selection Object.
In my following Code I get always Null for the Variable "Selected Question" which is bound to the Datatable with Selection.
The jsf as followed:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:composition template="mainTemplate.xhtml">
<ui:define name="contentTitle">Your Questions</ui:define>
<ui:define name="content">
<h:form id="formAllQuestion">
<p:growl id="allQuestionGrowl" showDetail="true"/>
<p:dataTable id="allQuestionsTable" var="question" value="#{allQuestionBean.allQuestionDataHelper}" paginator="true" rows="10"
selection="#{allQuestionBean.selectedQuestion}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{allQuestionBean.onRowSelect}" update=":formAllQuestion:AnswerToQuestionDialogTable :formAllQuestion:allQuestionGrowl"
oncomplete="questDialog.show()"/>
<p:ajax event="rowUnselect" listener="#{allQuestionBean.onRowUnselect}" update=":formAllQuestion:allQuestionGrowl"/>
<f:facet name="header">Select a Row to display your Question Details</f:facet>
<p:column headerText="QuestionID">
#{question.questionId}
</p:column>
<p:column headerText="Question Name">
#{question.questionName}
</p:column>
<p:column headerText="Question Description">
#{question.questionText}
</p:column>
<p:column headerText="Question Short Description">
#{question.questionShortText}
</p:column>
<p:column headerText="Author">
#{question.professor.profSurename} #{question.professor.profName}
</p:column>
</p:dataTable>
<p:dialog header="Question Details" widgetVar="questionDialog" resizable="true" id="questDialog"
showEffect="fade" hideEffect="fade" modal="true">
<p:dataTable id="AnswerToQuestionDialogTable" var="answer" value="#{allQuestionBean.answers}">
<f:facet name="header">
Hier kommt der QR_Code rein!
#{allQuestionBean.selectedQuestion.questionId} - #{allQuestionBean.selectedQuestion.questionName}
</f:facet>
<p:column headerText="Answer">
<h:outputText value="#{answer.answerText}"/>
</p:column>
<p:column headerText="Counts For this Answer">
<h:outputText value="Bis jetz noch nix!"/>
</p:column>
</p:dataTable>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
</html>
And the associated Bean Class (AllQuestionBean.class):
#ManagedBean(name = "allQuestionBean")
#ViewScoped
public class AllQuestionBean implements Serializable {
private static final long serialVersionUID = 7038894302985973905L;
#ManagedProperty(value = "#{questionDAO}")
private QuestionDAO questionDAO;
#ManagedProperty(value = "#{profSession.professor}")
private Professor professor;
#ManagedProperty(value = "#{answerDAO}")
private AnswerDAO answerDAO;
#ManagedProperty(value = "#{answeredDAO}")
private AnsweredDAO answeredDAO;
private List<Question> questions;
private Question selectedQuestion;
private List<Answer> answers;
private AllQuestionDataHelper allQuestionDataHelper;
public AllQuestionBean(){
System.out.println("Starting Bean: "+this.getClass().getName());
}
#PostConstruct
public void initVariables(){
questions = questionDAO.readByProfessor(professor);
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Question Selected", selectedQuestion.getQuestionId()+" -- "+selectedQuestion.getQuestionName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowUnselect(UnselectEvent event) {
FacesMessage msg = new FacesMessage("Question Selected", selectedQuestion.getQuestionId()+" -- "+selectedQuestion.getQuestionName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
//---GETTER and SETTER
public AllQuestionDataHelper getAllQuestionDataHelper() {
allQuestionDataHelper = new AllQuestionDataHelper(questions);
return allQuestionDataHelper;
}
public void setAllQuestionDataHelper(AllQuestionDataHelper allQuestionDataHelper) {
this.allQuestionDataHelper = allQuestionDataHelper;
}
public QuestionDAO getQuestionDAO() {
return questionDAO;
}
public void setQuestionDAO(QuestionDAO questionDAO) {
this.questionDAO = questionDAO;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public AnswerDAO getAnswerDAO() {
return answerDAO;
}
public void setAnswerDAO(AnswerDAO answerDAO) {
this.answerDAO = answerDAO;
}
public AnsweredDAO getAnsweredDAO() {
return answeredDAO;
}
public void setAnsweredDAO(AnsweredDAO answeredDAO) {
this.answeredDAO = answeredDAO;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public Question getSelectedQuestion() {
System.out.println("getSelectedQuestion");
return selectedQuestion;
}
public void setSelectedQuestion(Question selectedQuestion) {
System.out.println("Set selected Question: "+selectedQuestion);
this.selectedQuestion = selectedQuestion;
}
public List<Answer> getAnswers() {
answers = answerDAO.getAllAnswersForQuestion(selectedQuestion);
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
The Data Modell:
public class AllQuestionDataHelper extends ListDataModel<Question> implements SelectableDataModel<Question> {
public AllQuestionDataHelper() {
}
public AllQuestionDataHelper(List<Question> list) {
super(list);
}
#Override
public Object getRowKey(Question question) {
if(!(question == null)){
System.out.println("Your Questions --> Getting RowKey");
System.out.println("RowKey: "+question);
System.out.println("RowKey: "+question.getQuestionId());
}else{
System.out.println("Warning Row Key is null");
}
return question.getQuestionId();
}
#Override
public Question getRowData(String rowKey) {
System.out.println("Your Questions --> Getting RowData");
System.out.println("RowData: "+rowKey);
List<Question> questionList = (List<Question>) getWrappedData();
for(Question q : questionList){
if(rowKey.equals(q.getQuestionId())){
System.out.println("Returning "+q.getQuestionId());
return q;
}
}
return null;
}
}
I debugged a few runs and mentioned that the Variable "selectedQuestion" in AllQuestionBean.class is never set. Will say, the event Variable in "onRowSelect" holds a NULL-Object.
As you can see there are two Datatables in the *.xhtml. The first one will load normally, no problems. The onClick-Method of the Bean should launch a Dialog with the Second Datatable, but will quit with a Nullpointer.
For the Datatable I followed the Tutorial at Primefaces (http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionInstant.jsf)
Use rowKey attribute on p:dataTable.
rowKey is a unique Identifier that helps Primefaces engine to return the selected Object based on selection.
Usually the value you supply to the rowKey attribute is the unique property of the POJO that you are populating in to p:dataTable.
If you don't have any such unique fields in your POJO. Then its always useful to make one, for example: int rowId;, which you might increment and put in to POJO while you adding them to the List.

Resources