I was trying to implement sort functionality on primefaces dataTable.Sorting is working. But when I delete, update the dataTable items ,no effect (nothing changes) in dataTable. That is dataTable not getting cleared or refreshed.But in the database delete,update are occurring with out any issue.When I logged out and re-login, new list(dataTable) is fine.
employeeView.jsf:
<p:dataTable id="employees" value="#{employeeList.employees}"
var="employee" emptyMessage="No Employees found" rows="10"
paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" rowIndexVar="rowIndex">
<p:column sortBy="#{employee.firstName}">
<f:facet name="header">
<h:outputText value="First Name" />
</f:facet>
<h:outputText value="#{employee.firstName}">
</h:outputText>
</p:column>
<p:column sortBy="#{employee.lastName}">
<f:facet name="header">
<h:outputText value="Last Name" />
</f:facet>
<h:outputText value="#{employee.lastName}" />
</p:column>
</p:dataTable>
EmployeeList.java:
#Component("employeeList")
#SessionScoped
#Repository
public class EmployeeList implements Serializable {
private static final long serialVersionUID = -2417394435764260084L;
public static HibernateTemplate hibernateTemplate;
private List<Employee> employees = new ArrayList<Employee>();
#Autowired
public void setSessionFactory(SessionFactory sessionFactory)
{
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public List<Employee> getEmployees() {
if(employees.isEmpty()){
employees.addAll(empList());
}
return employees;
}
#SuppressWarnings("unchecked")
public List<Employee> empList() {
try
{
List <Employee> result = hibernateTemplate.find("from Employee");
return result;
}
finally {
//close the session and user-supplied JDBC connection
}
}
}
I have tried with #RequestScope,#ViewScope etc.But no effect.Where I went wrong?
Primefaces-3.0.M3 with JSF2 and Google Cloud SQL
Related
I'm trying to get selected values from a selectCheckboxMenu, but all I'm getting is null in the console. It doesn't work with selectOneMenu too. Here's my jsf form:
<h:form id="mmaster">
<p:dataTable
value="#{devicesBean.devices}"
var="dev"
widgetVar="dt"
border="1"
paginator="true"
paginatorPosition="top"
rows="10"
>
<f:facet name="header">Devices</f:facet>
<p:column headerText="UDN" sortBy="#{dev.deviceUDN}" filterBy="#{dev.deviceUDN}" filterMatchMode="contains" emptyMessage="No Devices Found">
<h:outputText value="#{dev.deviceUDN}" />
</p:column>
<p:column headerText="FriendlyName" sortBy="#{dev.deviceFriendlyName}" filterBy="#{dev.deviceFriendlyName}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceFriendlyName}" />
</p:column>
<p:column headerText="Model" sortBy="#{dev.deviceModel}" filterBy="#{dev.deviceModel}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceModel}" />
</p:column>
<p:column headerText="Manufacturer" sortBy="#{dev.deviceManufacturer}" filterBy="#{dev.deviceManufacturer}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceManufacturer}" />
</p:column>
<p:column headerText="Type" sortBy="#{dev.deviceType}" filterBy="#{dev.deviceType}" filterMatchMode="contains">
<h:outputText value="#{dev.deviceType}" />
</p:column>
<p:column headerText="Actions">
<p:selectCheckboxMenu value="#{devicesBean.selectAnnotations}">
<f:selectItems value="#{devicesBean.annotations}" />
</p:selectCheckboxMenu>
</p:column>
<p:column>
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#this">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
I wonder if there is a problem in the bean's scope, And this is my managed bean:
#ManagedBean
public class DevicesBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<Device> devices;
private List<String> annotations;
private List<String> selectAnnotations = new ArrayList<String>();
private Device device;
#EJB
IOntoProcessor iop;
#EJB
IDevicesDao idd;
public DevicesBean() {
}
#PostConstruct
public void init() {
setDevices(idd.getAllDevices());
setAnnotations(iop.getAllAnnotations());
}
public List<Device> getDevices() {
return devices;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
}
public List<String> getAnnotations() {
return annotations;
}
public void setAnnotations(List<String> annotations) {
this.annotations = annotations;
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
public List<String> getSelectAnnotations() {
return selectAnnotations;
}
public void setSelectAnnotations(List<String> selectAnnotations) {
this.selectAnnotations = selectAnnotations;
}
public void doSave() {
System.out.println(selectAnnotations);
System.out.println(device);
selectAnnotations = new ArrayList<String>();
}
}
You are trying to submit the form through the Button with value Annotate, which has been specified to process itself only:
This will only process the button and its associated form parameters, and no other element within the form.
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#this">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
Either remove the process="#this", or replace it with process="#form"
<p:commandButton value="Annotate" action="#{devicesBean.doSave}" process="#form">
<f:setPropertyActionListener value="#{dev}" target="#{devicesBean.device}" />
</p:commandButton>
Two, declare your managed bean scope: Either #RequestScope or #SessionScoped will work fine.
I'm trying to delete row in primefaces datatable from database. It's working fine in datatable, but after refreshing project the row value show up.I'm using http://www.mkyong.com/jsf2/how-to-delete-row-in-jsf-datatable/ example. Can anybody help?
index.xhtml
<p:growl id="messages" showDetail="true"/>
<p:dataTable var="u" value="#{logonTest.userList}" id="carList" editable="true">
<f:facet name="header">
In-Cell Editing
</f:facet>
<p:ajax event="rowEdit" listener="#{tableBean.onEdit}" update=":form:messages" />
<p:ajax event="rowEditCancel" listener="#{tableBean.onCancel}" update=":form:messages" />
<p:column headerText="Name" style="width:30%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.name}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.name}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Surname" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.surname}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.surname}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Username" style="width:24%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.username}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.username}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Description" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{u.description}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{u.description}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:6%">
<p:rowEditor />
<h:commandLink value="Delete" action="#{logonTest.deleteAction(u)}" />
</p:column>
</p:dataTable>
</h:form>
LogonTest.java
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
public String deleteAction(User user) {
userList.remove(user);
return null;
}
}
that because you remove it from the arraylist only not from the database
use em.remove(user)
Your delete action is only removing it from the scoped variable.
public String deleteAction(User user) {
userList.remove(user);
return null;
}
You need to also remove it from the database, via the entity manager. em.remove(object)
Try the following code with EntityManager using remove method.
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
public String deleteAction(User user) {
EntityManager em = emf.createEntityManager();
em.remove(user);
userList.remove(user);
return null;
}
}
My goal is to present a jsf page that has Create, Retrieve and Update features.
I decided to create different CDI beans and different composite components for each of this operations and then put it all together in the page.
So far so good, but i just finished and i discovered a really confusing bug, and i don't know how to fix it:
The CDI bean tool that does the CREATE operation is a #RequestScoped bean, so the input fields clean them selves after the request.(See the image bellow)
I have no problem at all with it(Just that warning i cant get rid off), it works fine.
The next gadget i created is a data table that can also edit the data. To do it i needed to use a #SessionScopped CDI bean.(See image below)
Here comes the problem:
When the page is rendered the #SessionScoped bean caches the data in the session, but when new data is inserted, using the #RequestScoped bean,the data goes to the data base but the datatable does not display the new entered values, because are not in the session.
So what should i do?
Here i will show you the two beans:
THE CREATE BEAN
#Named("subjectControllerCreate")
#RequestScoped
public class SubjectControllerCreate implements Serializable {
private Subject currentSubject;
#EJB
private SubjectFacade ejbFacade;
//INITIALIZATION
public SubjectControllerCreate() {
currentSubject = new Subject();
}
//CREATE
public String create() {
try {
currentSubject.setCreationDate(new Date());
getSubjectFacade().create(currentSubject);//Adds the current subject to the database!
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SubjectCreated"));
return "";//Can perform a redirect here if we want
//}
//return null;
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
THE UPDATE BEAN
#Named("subjectControllerUpdate")
#SessionScoped
public class SubjectControllerUpdate implements Serializable {
//Using DataModel<Subject> instead of List<Subject> is necessary in order to be able to get the current row.
private DataModel<Subject> subjects;
#EJB
private SubjectFacade ejbFacade;
//INITIALIZATION
#PostConstruct
public void init() {
subjects = new ListDataModel<Subject>(getSubjectFacade().findAll());
}
//RETRIEVE
public DataModel<Subject> retrieve() {
return subjects;
}
//UPDATE
public void update() {
getSubjectFacade().edit(subjects.getRowData());
}
//HELP METHODS
//RETURN THE FACADE FOR DATA MANIPULATION(Best practice)
private SubjectFacade getSubjectFacade() {
return ejbFacade;
}
//GETTERS AND SETTERS
public DataModel<Subject> getSubjects() {
return subjects;
}
public void setSubjects(DataModel<Subject> subjects) {
this.subjects = subjects;
}
}
Is it maybe possible to make the data table send some ajax request when detects that the Create dialog closes, to get the rest of the newly entered data?
If yes how could i do it?
This is the markup for my datatable:
<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:form>
<p:dataTable id="allSubjects" var="subject" value="#{subjectControllerUpdate.subjects}" paginator="true" rows="7" >
<p:ajax event="rowEdit" listener="#{subjectControllerUpdate.update()}"/>
<p:column headerText="Name" sortBy="#{subject.name}" style="width:200px" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.name}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.name}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.description}" headerText="Description">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.description}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.description}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.credits}" headerText="Credits" style="width:50px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.credits}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.credits}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Options" style="width:50px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</html>
Ill appreciate your help
Can't you just inject the #SessionScoped bean into the #RequestScoped bean and when create is clicked, call a method refresh in the #SessionScoped bean?
I am trying to figure out, how the primefaces in-cell editor works.
For some reason, it does not work. I just see it activating and also i can type, but the values do not change. What is missing?
<?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:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:form>
<p:dataTable id="allSubjects" var="subject" value="#{subjectControllerUpdate.retrieve()}" paginator="true" rows="7" >
<p:column headerText="Name" sortBy="#{subject.name}" style="width:200px" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.name}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.name}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.description}" headerText="Description">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.description}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.description}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column sortBy="#{subject.credits}" headerText="Credits" style="width:50px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{subject.credits}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{subject.credits}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Options" style="width:50px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</html>
This is the managed bean
package controllers;
import crudfacades.SubjectFacade;
import entities.Subject;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named("subjectControllerUpdate")
#SessionScoped
public class SubjectControllerUpdate implements Serializable {
private List<Subject> subjects;
private Subject currentSubject;
#EJB
private SubjectFacade ejbFacade;
//INITIALIZATION
public SubjectControllerUpdate() {
currentSubject = new Subject();
}
//RETRIEVE
public List<Subject> retrieve() {
return getSubjectFacade().findAll();
}
//UPDATE
//HELP METHODS
//RETURN THE FACADE FOR DATA MANIPULATION(Best practice)
private SubjectFacade getSubjectFacade() {
return ejbFacade;
}
//GETTERS AND SETTERS
public Subject getCurrentSubject() {
return currentSubject;
}
public void setCurrentSubject(Subject currentSubject) {
this.currentSubject = currentSubject;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
}
but when i click comfirm, the value in the UI is not changed
You've bound the value of the <p:dataTable> to retrieve() instead of getSubjects(). So every single getter call will get the values straight from the DB instead of the model.
and i see no changes in the database
You are not saving anything in the DB.
Fix your controller as follows:
#Named
#SessionScoped
public class SubjectControllerUpdate implements Serializable {
private DataModel<Subject> subjects;
#EJB
private SubjectFacade ejbFacade;
#PostConstruct
public void init() {
subjects = new ListDataModel<Subject>(ejbFacade.findAll());
}
public void save() {
ejbFacade.save(subjects.getRowData());
}
public List<Subject> getSubjects() {
return subjects;
}
}
with
<h:form>
<p:dataTable value="#{subjectControllerUpdate.subjects}" ...>
<p:ajax event="rowEdit" listener="#{subjectControllerUpdate.save}" />
...
</p:dataTable>
</h:form>
Using DataModel<Subject> instead of List<Subject> is necessary in order to be able to get the current row.
I have an entity with the following named query:
#NamedQuery(name = "findAllGarbage", query = "SELECT g.filename, g.description, g.uploadDate FROM Garbage g;")
The problem is that i want to pass that result to a dataTable to render, and i recieve NumberFormatException. I dont understand why because there are no numbers anywhere.
This is how the rest of the program looks like:
-The EJB that executes the query
#Stateless(name = "ejbs/SearchEJB")
public class SearchEJB implements ISearchEJB {
#PersistenceContext
private EntityManager em;
public List<Garbage> findAllGarbage() {
Query query = em.createNamedQuery("findAllGarbage");
List<Garbage> tmpGarbage = query.getResultList();
return tmpGarbage;
}
-The part of the JSF that displays the tableData:
<p:dataTable var="garbage" value="#{resultsController.allGarbage}" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
<h:outputText value="Filename" />
</f:facet>
<h:outputText value="#{garbage.filename}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{garbage.description}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Upload date" />
</f:facet>
<h:outputText value="#{garbage.uploadDate}" />
</p:column>
</p:dataTable>
-The managed bean that interacts with the JSF page:
#ManagedBean
#RequestScoped
public class ResultsController {
#EJB
private ISearchEJB searchEJB;
private Garbage garbage;
public List<Garbage> getAllGarbage() {
return searchEJB.findAllGarbage();
}
public Garbage getGarbage() {
return garbage;
}
public void setGarbage(Garbage garbage) {
this.garbage = garbage;
}
The error says:
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NumberFormatException: For input string: "filename"
I dont understand what is wrong with the file name.
------------------------------------UPDATE------------------------------------
I changed the JSF to this, and now i dont see the error. I see tha table data but empty:
<p:dataTable var="garbage" value="#{resultsController.allGarbage}" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
<h:outputText value="Filename" />
</f:facet>
<h:outputText value="#{garbage[4]}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{garbage[3]}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Upload date" />
</f:facet>
<h:outputText value="#{garbage[6]}" />
</p:column>
</p:dataTable>
The problem is caused by the fact that a query such as
SELECT g.filename, g.description, g.uploadDate FROM Garbage
returns an Object[] with filename, description and uploadDate as its elements.
If you want to access them as object properties (as you do in JSF), you need to query for the full object instead:
SELECT g FROM Garbage g