no records found in my jsf page - jsf-2

I am trying to retrive data from my database and it actually worked for another table but with this one there is only no records found without any error message in the log file here is my code :
#ManagedBean
#SessionScoped
public class AnnonceBean implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private List<SelectItem> anonItems;
private DataModel annonces;
private Annonce newAnnonce = new Annonce();
private Annonce editAnnonce;
private DaoAnnonce aDao = new DaoAnnonce();
public List<SelectItem> getAnonItems() {
if (anonItems == null) {
anonItems = new ArrayList<SelectItem>();
List<Annonce> annList = aDao.selectAll();
for (Annonce an : annList) {
anonItems.add(new SelectItem((Annonce) an, ((Annonce) an)
.getTitre()));
anonItems.add(new SelectItem((Annonce) an, ((Annonce) an)
.getContenu()));
anonItems.add(new SelectItem((Annonce) an, ((Annonce) an)
.getProfesseur().getPrenom()));
}
}
return anonItems;
}
public AnnonceBean() {
if (annonces == null) {
annonces = new ListDataModel();
annonces.setWrappedData(aDao.selectAll());
}
}
public String creer() {
return "add";
}
public String create() {
aDao.ajouter(newAnnonce);
newAnnonce = new Annonce();
annonces.setWrappedData(aDao.selectAll());
FacesMessage msg = new FacesMessage("Ajout effectué avec succés");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "list";
}
public String deleteGroupe() {
Annonce a = (Annonce) annonces.getRowData();
aDao.supprimer(a);
FacesMessage msg = new FacesMessage("Suppression effectué avec succés");
FacesContext.getCurrentInstance().addMessage(null, msg);
return null;
}
public String editAnnonce() {
editAnnonce=(Annonce)annonces.getRowData();
return "edit";
}
public String updateAnnonce(){
aDao.modifier(editAnnonce);
annonces.setWrappedData(aDao.selectAll());
FacesMessage msg = new FacesMessage("Modification effectué avec succés");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "list";
}
and this is my Dao class code
public class DaoAnnonce {
private static final String JPA_UNIT_NAME="Portail";
private EntityManager entityManager;
protected EntityManager getEntityManager() {
if (entityManager == null) {
entityManager = Persistence.createEntityManagerFactory(
JPA_UNIT_NAME).createEntityManager();
}
return entityManager;
}
public void ajouter(Annonce a)
{
EntityTransaction tx = getEntityManager().getTransaction();
tx.begin();
entityManager.persist(a);
tx.commit();
}
public void modifier(Annonce a)
{
EntityTransaction tx = getEntityManager().getTransaction();
tx.begin();
entityManager.merge(a);
tx.commit();
}
public void supprimer(Annonce a)
{
EntityTransaction tx = getEntityManager().getTransaction();
tx.begin();
a=entityManager.merge(a); // important
entityManager.remove(a);
tx.commit();
}
public List<Annonce > selectAll() {
List<Annonce > annonces =getEntityManager().createQuery("select a from Annonce a").getResultList();
return annonces;
}
and this the jsf code
<p:tab title="Annonces">
<p:dataTable var="annonce" value="#{annonceBean.annonces}"
editable="true">
<p:ajax event="rowEdit" listener="#{tableBean.onEdit}" />
<p:ajax event="rowEditCancel" listener="#{tableBean.onCancel}" />
<p:column headerText="Titre" style="width:30%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{annonce.titre}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{annonce.titre}" style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Contenu" style="width:20%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{annonce.contenu}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{annonce.contenu}" style="width:100%"
label="contenu" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Professeur" style="width:24%">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{annonce.prenom}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{annonce.prenom}" style="width:100%"
label="prenom" />
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
</p:tab>
I am working on eclipse and i am using primefaces for the components

In your bean AnnonceBean there is no method called getAnnonces(), but there is a method getAnonItems() returning a List<SelectItem> which is probably what you want. If this is the case, #{annonceBean.annonces} should be replaced by #{annonceBean.anonItems}.

Related

Primefaces values from p:dialog do not update p:dataTable

When I try to add values to p:dataTable using p:dialog, the values are not added to the table (not even update the bean).
The xhtml file is
<h:form>
<p:dialog id="dialog" header="Goal" widgetVar="goalDlg"
resizable="false" modal="true" appendTo="#(body)" >
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Minute:" />
<p:inputText value="#{matchBean.minute}" immediate="true" />
<p:outputLabel value="Is self:" />
<p:selectBooleanCheckbox value="#{matchBean.self}" immediate="true" />
</h:panelGrid>
<f:facet name="footer">
<p:commandButton value="OK" action="#{matchBean.addTheGoal}" />
</f:facet>
</p:dialog>
<h1>Add Match Players</h1>
<p:panelGrid columns="2">
<p:dataTable value="#{matchBean.homePlayers}" var="homePlayer" >
<f:facet name="header">
#{matchBean.homeGroupName}
</f:facet>
<p:column>
<f:facet name="header">Play</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Player Name</f:facet>
<p:outputLabel value="#{homePlayer.name}" />
</p:column>
<p:column>
<f:facet name="header">Start</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Yellow</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Red</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Rep</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Min</f:facet>
<p:inputText />
</p:column>
<p:column>
<f:facet name="header">Goals</f:facet>
<p:outputLabel value="#{homePlayer.yield}" />
<p:commandButton value="Add" action="#{matchBean.addGoal(homePlayer, true)}" />
</p:column>
</p:dataTable>
<p:dataTable value="#{matchBean.guestPlayers}" var="guestPlayer">
<f:facet name="header">
#{matchBean.guestGroupName}
</f:facet>
<p:column>
<f:facet name="header">Play</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Player Name</f:facet>
<p:outputLabel value="#{guestPlayer.name}" />
</p:column>
<p:column>
<f:facet name="header">Start</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Yellow</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Red</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Rep</f:facet>
<p:selectBooleanCheckbox />
</p:column>
<p:column>
<f:facet name="header">Min</f:facet>
<p:inputText />
</p:column>
<p:column>
<f:facet name="header">Goals</f:facet>
<p:outputLabel value="#{guestPlayer.yield}" />
<p:commandButton value="Add" action="#{matchBean.addGoal(guestPlayer, false)}" />
</p:column>
</p:dataTable>
</p:panelGrid>
</h:form>
and relevant code from the managed bean:
#ManagedBean
#SessionScoped
public class MatchBean {
...
private int currPlayerId = 0;
private boolean isHomeGroup = false;
public void addGoal(MatchPlayer player, Boolean isHomeGroup) {
currPlayerId = player.getId();
this.isHomeGroup = isHomeGroup;
RequestContext.getCurrentInstance().execute("PF('goalDlg').show();");
}
public void addTheGoal() {
MatchPlayer[] players = null;
if (isHomeGroup) {
players = homePlayers;
} else {
players = guestPlayers;
}
for (MatchPlayer player : players) {
if (player.getId() == currPlayerId) {
MatchGoal goal = new MatchGoal(minute, self);
player.addGoal(goal);
System.out.println("Goal added at minute " + minute + ", self = " + self);
break;
}
}
RequestContext.getCurrentInstance().execute("PF('goalDlg').hide();");
}
...
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
System.out.println("Setting minute to " + minute);
this.minute = minute;
}
and MatchPlayer:
package com.ransh.soccer.dto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MatchPlayer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private boolean played;
private String name;
private boolean started;
private boolean yellowCard;
private boolean redCard;
private boolean replaced;
private int minute;
private List<MatchGoal> matchGoals = null;
/**
* C'tor
*/
public MatchPlayer(int id, String name) {
this.id = id;
this.name = name;
played = false;
started = false;
yellowCard = false;
redCard = false;
replaced = false;
minute = 0;
matchGoals = new ArrayList<MatchGoal>();
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the played
*/
public boolean isPlayed() {
return played;
}
/**
* #param played the played to set
*/
public void setPlayed(boolean played) {
this.played = played;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the started
*/
public boolean isStarted() {
return started;
}
/**
* #param started the started to set
*/
public void setStarted(boolean started) {
this.started = started;
}
/**
* #return the yellowCard
*/
public boolean isYellowCard() {
return yellowCard;
}
/**
* #param yellowCard the yellowCard to set
*/
public void setYellowCard(boolean yellowCard) {
this.yellowCard = yellowCard;
}
/**
* #return the redCard
*/
public boolean isRedCard() {
return redCard;
}
/**
* #param redCard the redCard to set
*/
public void setRedCard(boolean redCard) {
this.redCard = redCard;
}
/**
* #return the replaced
*/
public boolean isReplaced() {
return replaced;
}
/**
* #param replaced the replaced to set
*/
public void setReplaced(boolean replaced) {
this.replaced = replaced;
}
/**
* #return the minute
*/
public int getMinute() {
return minute;
}
/**
* #param minute the minute to set
*/
public void setMinute(int minute) {
this.minute = minute;
}
public void addGoal(MatchGoal goal) {
matchGoals.add(goal);
}
public List<MatchGoal> getGoals() {
return matchGoals;
}
public String getYield() {
if (matchGoals.size() == 0) {
return "No Goals";
}
StringBuilder yield = new StringBuilder();
for (MatchGoal goal : matchGoals) {
if (yield.length() > 0) {
yield.append(", ");
}
if (goal.isSelf()) {
yield.append("S(" + goal.getMinute() + ")");
} else {
yield.append(goal.getMinute());
}
}
return yield.toString();
}
}
I have 2 problems with this code:
1. setMinute() is not called at all.
2. homePlayer.yield and guestPlayer.yield are never updated.
How can I fix these problems?
Try to remove immediate="true" from form components in the dialog. Also, remove appendTo="#(body) from the dialog, or add a <h:form> in it. Since you are appending the dialog to the body, it gets out of <h:form> of your page. You can check this if you inspect the DOM in your browser.

p:dataTable how to stay in edit mode?

I'm using primefaces 3.5 and watching a strange datatable behavior when editing data.
If I enter wrong data in 'year' field and click on the tick I get a message about mistake.
But if I don't click on the tick and click on the 'Add row' button I don't get a message. Only new row is added.
I expect to stay in edit mode. How to solve this problem?
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="In cell editing" />
<p:dataTable id="inCellEditing" var="car" value="#{dataTableController.cars}" rowKey="#{car.name}" editable="true">
<p:ajax event="rowEdit" listener="#{dataTableController.onEdit}" update=":mainForm:growl" />
<p:ajax event="rowEditCancel" listener="#{dataTableController.onCancel}" update=":mainForm:growl" />
<p:column headerText="Year">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{car.year}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{car.year}">
<p:ajax event="blur" update="#this"/>
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Name">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{car.name}" />
</f:facet>
<f:facet name="input">
<h:selectOneMenu value="#{car.name}" >
<f:selectItems value="#{dataTableController.carNames}"
var="name"
itemLabel="#{name}"
itemValue="#{name}" />
</h:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Actions">
<p:rowEditor />
</p:column>
</p:dataTable>
<p:commandButton action="#{dataTableController.addRow()}" value="Add row" ajax="false"/>
</h:panelGrid>
public class DataTableController implements Serializable {
private List<Car> cars;
private Car selectedCar;
private Car[] selectedCars;
private List<Car> selectedCarsList;
private SelectItem[] carNamesOptions;
public DataTableController() {
cars = new ArrayList<Car>(CarConverter.cars.values());
}
public String[] getCarNames() {
return CarConverter.cars.keySet().toArray(new String[0]);
}
public SelectItem[] getCarNamesAsOptions() {
carNamesOptions = createFilterOptions(CarConverter.cars.keySet().toArray(new String[0]));
return carNamesOptions;
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
public void onEdit(RowEditEvent event) {
MessageUtil.addInfoMessage("car.edit", ((Car) event.getObject()).getName());
}
public void onCancel(RowEditEvent event) {
MessageUtil.addInfoMessage("car.edit.cancelled", ((Car) event.getObject()).getName());
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car[] selectedCars) {
this.selectedCars = selectedCars;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public List<Car> getSelectedCarsList() {
return selectedCarsList;
}
public void setSelectedCarsList(List<Car> selectedCarsList) {
this.selectedCarsList = selectedCarsList;
}
public void addRow(){
cars.add(new Car("",0));
}
}

To fetch checkbox selected values from primefaces datatable to managed bean

I am trying to fetch the checkbox selected values selectedCars from primefaces datatable to my managed bean named TableBean.I am getting null pointer exception at the point where I am trying to fetch the values in the function getSelection() please help me with this
My JSF page:
<h:form id="form">
<p:dataTable id="multiCars" var="car"
value="#{tableBean.mediumCarsModel}" paginator="true" rows="10"
selection="#{tableBean.selectedCars}">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:2%" />
<p:column headerText="Model" style="width:25%">
#{car.model}
</p:column>
<p:column headerText="Year" style="width:25%">
#{car.year}
</p:column>
<p:column headerText="Manufacturer" style="width:24%">
#{car.manufacturer}
</p:column>
<p:column headerText="Color" style="width:24%">
#{car.color}
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View"
icon="ui-icon-search" update=":form:displayMulti"
oncomplete="multiCarDialog.show()" />
</f:facet>
</p:dataTable>
<p:dialog id="multiDialog" header="Car Detail"
widgetVar="multiCarDialog" height="300" showEffect="fade"
hideEffect="explode">
<p:dataList id="displayMulti" value="#{tableBean.selectedCars}"
var="selectedCar">
Model: #{selectedCar.model}, Year: #{selectedCar.year}
</p:dataList>
</p:dialog>
</h:form>
My managed bean
#SessionScoped
#ManagedBean
public class TableBean implements Serializable {
private List<Car> cars;
private Car[] selectedCars;
private CarDataModel mediumCarsModel;
Connection connection;
Statement stmt;
ResultSet rs;
public TableBean() {
cars = new ArrayList<Car>();
getCars();
getSelection();
mediumCarsModel = new CarDataModel(cars);
}
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car[] selectedCars) {
this.selectedCars = selectedCars;
}
public void getCars() {
int i = 0;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:jtds:sqlserver://cvgapp106I/dev2_LPSR");
System.out.println("connected to the database");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select * from test");
while(rs.next()) {
cars.add(i,new Car(rs.getString("Model"),rs.getInt("Year"),rs.getString("Manufacturer"),rs.getString("Color")));
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void getSelection() {
System.out.println(selectedCars[0].getModel());
}
public CarDataModel getMediumCarsModel() {
return mediumCarsModel;
}
public void setMediumCarsModel(CarDataModel mediumCarsModel) {
this.mediumCarsModel = mediumCarsModel;
}
}
public void getSelection() {
System.out.println(selectedCars[0].getModel());
}
This will throw NullPointerException if the list is empty.
If you really want to use this then you should try check if the list not null
if(selectedCars!=null && !selectedCars.isEmpty()){
System.out.println(selectedCars[0].getModel());
}
Do not call getSelection() in your constructor. There selectedCars will be always null

NumberFormatException for input String in datatable

I have the following method in my DAO where I retrieve a list of persons :
public List<Personne> getAllUsers() {
Query query = em.createQuery("SELECT p FROM Personne p where TYPE(p) =Utilisateur");
#SuppressWarnings("unchecked")
List <Personne> personnes = query.getResultList();
return personnes;
}
I want to show the list of persons in a datatable :
<p:dataTable value="#{desacBean.users}" var="us" paginator="true" selection="# {desacBean.selectedUser}" selectionMode="single" rowKey="#{desacBean.getId(us)}}" first="1">
<p:ajax event="rowSelect" listener="#{desacBean.onUserSelect}"/>
<p:column>
<f:facet name="n">
<h:outputText value="nom" />
</f:facet>
<h:outputText value="#{us.nom}"/>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="prenom" />
</f:facet>
<h:outputText value="#{us.prenom}"/>
</p:column>
</p:dataTable>
my BEAN :
#ManagedBean(name="desacBean")
#SessionScoped
public class DesactiveBean implements Serializable{
private static final long serialVersionUID = 1L;
private List<Personne> users = new ArrayList<Personne>();
private Personne selectedUser;
private boolean panelRendered;
UserDAO daoUser = new UserDaoImpl();
public void rowSelect(SelectEvent event){
selectedUser = (Personne)event.getObject();
System.out.println("selectedUser = "+selectedUser.getNom_ut());
this.panelRendered = true;
}
public int getId(Personne car)
{
return System.identityHashCode(car);
}
public void onUserSelect(SelectEvent event){
this.selectedUser = (Personne)event.getObject();
System.out.println("selectedUser = "+selectedUser.getNom_ut());
}
I have the following error when trying to show this dataTable :
java.lang.NumberFormatException: For input string: "prenom"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
For input string: "prenom"
how can I fix it?
You'll probably encountering the same issue as the question answered here: NumberFormatException for input String

Primefaces Collector Remove not working

I am testing the primefaces collector example given in Showcase for my code
I read somewhere that its necessary to override the equals and hashcode method for that.
Even after overriding the methods , I am still getting the same error.
Kindly tell me whats wrong in my code
User.java
#ManagedBean
public class User implements Serializable{
public String name;
public String designation;
public String division;
public User(String name,String division){
setName(name);
setDivision(division);
}
public User(){
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDivision() {
return division;
}
public void setDivision(String userDivision) {
this.division = userDivision;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
commApprover.java
#ManagedBean
#ViewScoped
public class CommApprover implements Serializable{
private User approver = new User();
private List<User> approvers = new ArrayList<User>();
public String reinit() {
approver = new User();
return null;
}
public User getApprover() {
return approver;
}
public void setApprover(User approver) {
this.approver = approver;
}
public List<User> getApprovers() {
return approvers;
}
public void setApprovers(List<User> approvers) {
this.approvers = approvers;
}
#Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
if (approver!= null ? !approver.equals(this.approver) : this.approver != null)
return false;
return true;
}
#Override
public int hashCode()
{
int result = approver.hashCode();
return result;
}
}
index.xhtml
<p:growl id="msgs" />
<p:panel header="Approval Route ">
<h:panelGrid columns="3" id="grid">
<h:outputText value="Name*" />
<h:outputText value="Designation*" />
<h:outputText value="Division*" />
<p:inputText id="app_name" value="#{commApprover.approver.name}" required="true"/>
<p:inputText id="app_designation" value="#{commApprover.approver.designation}" required="true"/>
<p:inputText id="app_division" required="true" value="# {commApprover.approver.division}" />
<p:commandButton id="btn_add" value="Add" update="approvers #parent" action="#{commApprover.reinit}" >
<p:collector value="#{commApprover.approver}" addTo="#{commApprover.approvers}" />
</p:commandButton>
</h:panelGrid>
</p:panel>
<p:outputPanel id="approvers">
<p:dataTable id="approversTable" value="#{commApprover.approvers}" var="approver">
<p:column>
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{approver.name}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Designation" />
</f:facet>
<h:outputText value="#{approver.designation}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Division" />
</f:facet>
<h:outputText value="#{approver.division}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Operation" />
</f:facet>
<p:commandLink ajax="true" value="Remove" update=":appform:approvers" process=":appform:approvers">
<p:collector value="#{approver}" removeFrom="#{commApprover.approvers}" />
</p:commandLink>
</p:column>
</p:dataTable>
</p:outputPanel>
</h:form>
This post is old but I ran into the same problem and after some debuging I found out that this problem is related to incorrectly implemented hashCode and equals, when using converters or p:collector you have to implement hashCode and equals to compare all fields in your entity otherwise it fails even if the item you are trying to remove is the correct one. Also it is recomended that you override those properties in your Pojo not in you ManagedBean. This post helped me to understand the problem https://blog.art-of-coding.eu/jsf-converters-and-equals-hashcode/

Resources