Update jsf growl message from load method of LazyDataModel - jsf

I need to display a message when LazyDataModel load method loads the data. I am using primefaces growl to display the message and updating it from load method using the below code, but It is not working (not seeing any message on UI). Please suggest what I am doing wrong, It seems something related to the asynchronous behaviour of load method but I am not sure how to fix it.
JSF Bean -
#ManagedBean(name = "cData")
#ViewScoped
public class DataPage implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2193735279937686495L;
#PostConstruct
public void init() {
FacesContext.getCurrentInstance().addMessage("growl-sticky", new
FacesMessage(FacesMessage.SEVERITY_INFO, "Sticky Message",
"Message Content from init"));
loadData();
}
private void loadData() {
FacesContext.getCurrentInstance().addMessage("growl-sticky", new
FacesMessage(FacesMessage.SEVERITY_INFO, "Sticky Message",
"Message loadData before load"));
setMobiles(new LazyDataModel<Mobile>() {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public List<Mobile> load(int first, int pageSize,
String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
List<Mobile> data = new DataRepo().getMobileData();
mobiles.setRowCount(data.size());
FacesContext.getCurrentInstance().addMessage("growl-sticky", new
FacesMessage(FacesMessage.SEVERITY_INFO, "Sticky Message",
"Message Content from load"));
return data;
}
#Override
public Mobile getRowData(String rowKey) {
// some code
}
#Override
public Object getRowKey(Mobile object) {
// some code
}
});
}
public LazyDataModel<Mobile> getMobiles() {
return mobiles;
}
public void setMobiles(LazyDataModel<Mobile> mobiles) {
this.mobiles = mobiles;
}
private LazyDataModel<Mobile> mobiles = null;
}
xhtml 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:c = "http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>DataTable tag Example</title>
</h:head>
<h:body>
<h3>Mobile Details</h3>
<h:form>
<c:metadata>
<c:viewAction action="#{cData.showSticky}" />
</c:metadata>
<p:growl id="growl-sticky" showDetail="true" sticky="true" autoUpdate="true"/>
<p:commandButton actionListener="#{cData.showSticky}"
update="growl-sticky" value="Info" style="width: 10rem"
styleClass="ui-button-help" />
<h:dataTable value="#{cData.mobiles}" var="mobile" border="2" paginator="true" rows="10"
lazy="true">
<h:column>
<c:facet name="header">Name</c:facet>
#{mobile.companyname}
</h:column>
<h:column>
<c:facet name="header">Model Number</c:facet>
#{mobile.modelnumber}
</h:column>
<h:column>
<c:facet name="header">Color</c:facet>
#{mobile.color}
</h:column>
<h:column>
<c:facet name="header">Quantity</c:facet>
#{mobile.quantity}
</h:column>
<h:column>
<c:facet name="header">Price</c:facet>
#{mobile.price}
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>

The issue why your message doesn't show up is because of the phase when Load is called. Explanation and workaround below.
The load method is invoked in RENDER_RESPONSE phase, which is inconvenient because error messages could occur here and they would not typically be rendered because p:messages are in most cases rendered as one of first components.
Issue: https://github.com/primefaces/primefaces/issues/3501
Workaround: https://github.com/primefaces/primefaces/issues/3501#issuecomment-469731529

Related

JSF checkbox value not sent to bean

While the view can get all values from the bean, when a checkbox (h:selectBooleanCheckbox) is toggled the bean is not updated. The setSelected() method in Item is never called from the view.
I've tried changing the scope of the bean to application, using a map instead of a value for the selected property and a foolish attempt at writing my own ajax javascript function.
The application I'm working with is a bit legacy so I'm using Tomcat 6, JSF 1.2 and Richfaces 3.3.3.Final.
It seems like it should be simple, I think I'm missing something obvious, but I've been at this for two days and can't figure out why the bean isn't updated.
My view is:
<!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:c="http://java.sun.com/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<head>
<title>JSF</title>
</head>
<body>
<h:form id="tableForm">
<rich:dataTable id="table" value="#{managedBean}" var="item" width="100%">
<rich:column label="Select" align="center" width="40px" >
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:selectBooleanCheckbox value="#{item.selected}" >
<a4j:support execute="#this" event="onclick" ajaxSingle="true"/>
</h:selectBooleanCheckbox>
</rich:column>
<rich:column label="Name" align="center" width="40px">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{item.name}" />
</rich:column>
</rich:dataTable>
</h:form>
</body>
</html>
I have a managed bean ItemBean in session scope:
import org.richfaces.model.ExtendedTableDataModel;
public class ItemBean extends ExtendedTableDataModel<Item>{
public ItemBean() {super(new ItemProvider());}
}
ItemProvider is:
import org.richfaces.model.DataProvider;
public class ItemProvider implements DataProvider<Item>{
private List<Item> items = new ArrayList<Item>();
public ItemProvider(){
for(int i = 0; i < 10; i++){
items.add(new Item(i, "Item "+i));
}
}
public Item getItemByKey(Object key) {return items.get((Integer)key);}
public List<Item> getItemsByRange(int fromIndex, int toIndex) {
return new ArrayList<Item>(items.subList(fromIndex, toIndex));
}
public Object getKey(Item arg0) {return arg0.getId();}
public int getRowCount() {return items.size();}
}
and Items are:
public class Item {
private final int id;
private final String name;
private boolean selected;
public Item(int id, String name) {
this.id = id;
this.name = name;
selected = false;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public boolean isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
}
I would assume, that your vanilla html, head and body tags might cause this.
Ajax-stuff (javascript) sometimes has to go into the <head> section of the page (along with required script references). Because JSF is working with components, it needs to insert the javascript required for a certain component at the time the component is added to the underlaying Object-Model.
Therefore JSF itself needs to manage the html, head and body tags.
So, instead of creating them as vanilla-html, use the proper<h:html>, <h:body> and <h:head> tags, which will handover this task to JSF. This way, the required javascript code for your onclick-event handler should be generated and the checkbox should work as expected.
The issue was that I hadn't set up my web.xml properly.
I was missing the following which routes the request to richfaces:
<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>

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

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>

How to display a simple primefaces datagrid

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

h:selectBooleanCheckBox action on select

I have a <h:selectBooleanCheckBox> as part part of my JSF which I want to run a bean method when it's state has changed from unchecked to checked.
I have the following controller bean
#Named
#ViewScoped
public class UserController {
#Inject
private UserService userService;
#Inject
private LocationService locationService;
private UserFilter userFilter;
private List<User> users;
private List<Location> locations;
#PostConstruct
public void init() {
users = userService.listAll();
locations = locationService.listAll();
userFilter = new UserFilter();
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public void listAllUsers() {
users = userService.listAll();
}
public void findUsers() {
// code that uses the UserFilter
// to decide which user filter find method to use
}
}
The UserFilter is a simple DTO
public class UserFilter {
private boolean allUsers = true;
private String username;
private String location;
//getters and setters
}
And my JSF has is like so
<?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://xmlns.jcp.org/jsf/core">
<h:head>
<title>Users</title>
</h:head>
<h:body>
<h1>Users</h1>
<h:form id="filterForm">
<h:selectBooleanCheckbox id="selectAll" value="#{userController.userFilter.allUsers}" title="allUsers">
<f:ajax render="filterGrid"/>
</h:selectBooleanCheckbox><h:outputText value ="All users"/>
<h:panelGrid id="filterGrid" columns="3">
<h:inputText id="userName" value="#{userController.userFilter.userName}" disabled="#{userController.userFilter.allUsers}"/>
<h:selectOneMenu id="selectLocation" value="#{userController.userFilter.location}" disabled="#{userController.userFilter.allUsers}">
<f:selectItems value="#{userController.locations}" var="location" itemValue="#{location.location}" itemLabel="#{location.location}"/>
</h:selectOneMenu>
<h:commandButton value="Filter" disabled="#{userController.userFilter.allUsers}" action="#{userController.findUsers()}"/>
</h:panelGrid>
</h:form>
<h:form rendered="#{not empty userController.users}">
<h:dataTable value="#{userController.users}" var="user">
<h:column>#{user.name}</h:column>
<h:column>#{user.location.location}</h:column>
<h:column><h:commandButton value="delete" action="#{userController.delete(user)}"/></h:column>
</h:dataTable>
</h:form>
<h:panelGroup rendered="#{empty userController.users}">
<p>Table is empty! Please add new items.</p>
</h:panelGroup>
<h3>Add user</h3>
<h:form id="user">
<p>Value: <h:inputText id="name" /></p>
<p>
<h:commandButton value="add" action="#{userController.add(param['user:name'])}"/>
</p>
</h:form>
</h:body>
</html>
As you can see by default it lists all users, then when the checkbox is unchecked you have the option to filter on username/location.
What I want is for the check box to run the userController.listAllUsers() method when it's state moves from unchecked to checked.
And a small additional question, how do I get the checkbox to appear in the same row as the panel grid items?
I have a habit of answering my own questions it seems! I needed an additional <f:ajax tag that rendered the user form and had the listener attribute set
So something like
<h:selectBooleanCheckbox id="selectAll" value="#{userController.userFilter.allUsers}" title="allUsers">
<f:ajax render="filterGrid"/>
<f:ajax render="usersForm" listener="#{userController.listAllUsers()}"/>
</h:selectBooleanCheckbox><h:outputText value ="All users"/>

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