p:dataTable how to stay in edit mode? - jsf-2

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));
}
}

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.

reinitialize session bean (a bean in sessionScopped) in JSF2

I am using JSF 2.0 , I have a bean opcD (#SessionScoped). since I have defined the bean in SessionScoped after submitting the form and returning to the page the data remains inside the fields that is logic! But I would like to reinitialize my bean if I return again inside it.
But I do not want to destroy the session!
#ManagedBean(name="opcD")
#SessionScoped
public class NewOPCDetailBean implements Serializable {
Please find in below a part of my cod. I go from page (newopcheadpage.xhtml) relevant to opc managedBean to page (newopcdetailpage.xhtml)relevant to managedBean opcD. After submiting page(newopcdetailpage.xhtml) if I want to return to page (newopcheadpage.xhtml), I would like to see the fields blank(beans become reinitialized ).
#ManagedBean(name="opc",eager = true) #SessionScoped
public class NewOPCHeadBean implements Serializable {
private long partID;
private String partDesc;
private String taskDesc;
private Date date;
private String opcDesc;
private List<Part> partList;
public long getPartID() {
return partID;
}
public void setPartID(long partID) {
this.partID = partID;
}
public String getPartDesc() {
return partDesc;
}
public void setPartDesc(String partDesc) {
this.partDesc = partDesc;
}
public String getTaskDesc() {
return taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public Date getDate() {
return new Date();
}
public void setDate(Date date) {
this.date = new Date();
}
public String getOpcDesc() {
return opcDesc;
}
public void setOpcDesc(String opcDesc) {
this.opcDesc = opcDesc;
}
public List<Part> getPartList() {
return partList;
}
public void setPartList(List<Part> partList) {
this.partList = partList;
}
public List<Part> getPartsList(ActionEvent e)
{
HibernateDA hDA = new HibernateDA();
partList = hDA.partsList();
return partList;
}
public void showPartDesc()
{
HibernateDA hDA = new HibernateDA();
partDesc = hDA.showPartDescription(partID);
setPartDesc(partDesc);
}
public String submit()
{
return "/pages/admin/newopcdetailpage";
}
public void resetBean()
{
opcDesc="";
partID=0;
partDesc="";
}
}
#ManagedBean(name="opcD") #ViewScoped
public class NewOPCDetailBean implements Serializable {
private long partID;
private String taskDesc;
private long partNumber;
private Part part;
private Date date;
private String opcDesc;
private long task_opc_number;
private long task_nominal_time;
private OPCDetail opcDetail;
private List<Part> partList;
private static final ArrayList<OPCDetail> opcDetailList = new ArrayList<OPCDetail>();
//private static ArrayList<OPCDetail> opcDetailList = new ArrayList<OPCDetail>();
public ArrayList<OPCDetail> getOpcDetailList() {
return opcDetailList;
}
public long getPartID() {
return partID;
}
public void setPartID(long partID) {
this.partID = partID;
}
public long getPartNumber() {
return partNumber;
}
public void setPartNumber(long partNumber) {
this.partNumber = partNumber;
}
public Part getPart() {
return part;
}
public void setPart(Part part) {
this.part = part;
}
public String getTaskDesc() {
return taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public long getTask_nominal_time() {
return task_nominal_time;
}
public long getTask_opc_number() {
return task_opc_number;
}
public void setTask_opc_number(long task_opc_number) {
this.task_opc_number = task_opc_number;
}
public void setTask_nominal_time(long task_nominal_time) {
this.task_nominal_time = task_nominal_time;
}
public OPCDetail getOpcDetail() {
return opcDetail;
}
public void setOpcDetail(OPCDetail opcDetail) {
this.opcDetail = opcDetail;
}
public List<Part> getPartList() {
return partList;
}
public void setPartList(List<Part> partList) {
this.partList = partList;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getOpcDesc() {
return opcDesc;
}
public void setOpcDesc(String opcDesc) {
this.opcDesc = opcDesc;
}
public List<Part> getPartsList(ActionEvent e)
{
HibernateDA hDA = new HibernateDA();
partList = hDA.partsList();
return partList;
}
public void takePartNumber(ActionEvent e) throws Exception
{
Map m = e.getComponent().getAttributes();
partID = (Long)m.get("pID");
HibernateDA hDA = new HibernateDA();
part = hDA.takePart(partID);
partNumber = part.getPart_number();
opcDesc = (String) m.get("opcDesc");
date = (Date) m.get("opcDate");
}
public void addAction()
{
OPCDetail opcDetail1 = new OPCDetail(this.task_nominal_time,this.taskDesc);
int i = 0;
int j=0;
if (opcDetailList != null){
while (i < opcDetailList.size())
{
String tDesk = this.taskDesc.toLowerCase();
if (opcDetailList.get(i).getTask_desc().equals(tDesk))
{
j = 1;
break;
}
i++;
}
if(j == 0)
{
opcDetailList.add(opcDetail1);
}
}
taskDesc = "";
task_nominal_time = 0;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Edited",((OPCDetail) event.getObject()).getTask_desc());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Item Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
opcDetailList.remove((OPCDetail) event.getObject());
}
public void resetBean()
{
taskDesc = "";
task_nominal_time=0;
}
public String submitNewOPC()
{
int i = 0;
List<OPCDetail> opcDetailList1 = new ArrayList<OPCDetail>();
if (opcDetailList != null && opcDetailList.size() != 0){
while (i < opcDetailList.size())
{
OPCDetail opcDetail1 = new OPCDetail(i+1,opcDetailList.get(i).getTask_nominal_time(),opcDetailList.get(i).getTask_desc());
opcDetailList1.add(opcDetail1);
i++;
}
HibernateDA hDA = new HibernateDA();
OPC opc1 = new OPC();
opc1.setOpc_date(date);
opc1.setOpc_desc(opcDesc);
opc1.setPart(part);
opc1.setListOfTasks(opcDetailList1);
hDA.addNewOPC(opc1);
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#opcD}");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("#opc}");
return "/index?faces-redirect=true";
}
}
<div style="border-bottom:2px solid #FFF">
<ui:insert name="header" >
<ui:include src="/header.xhtml" />
</ui:insert>
</div>
<div style="margin:0px 380px 0px 0px">
<h:form>
<p:panel header="Add New OPC" style="font-size: .6em">
<p:messages autoUpdate="true"/>
<h:panelGrid id="grid" columns="2" cellpadding="5">
<h:outputLabel for="opcDate" value="Date (dd-MM-yyyy):" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDate" value="#{opc.date}" required="true" label="Date(dd-MM-yyyy):" disabled="true">
<f:convertDateTime type="date" pattern="dd-MM-yyyy"/>
</p:inputText>
<p:message for="opcDate" />
<h:outputText value="" />
<h:outputLabel for="opcDesc" value="OPC Description:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDesc" value="#{opc.opcDesc}" required="true" label="OPC Description"/>
<p:message for="opcDesc" />
<h:outputText value="" />
<h:outputText value="Part Number " style="font-weight:bold; font-size: .8em" />
<p:selectOneMenu value="#{opc.partID}" required="true">
<p:ajax listener="#{opc.showPartDesc()}" update="partdesc" />
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{opc.partList}" var="parts" itemLabel="#{parts.part_number}" itemValue="#{parts.id}"/>
</p:selectOneMenu>
<h:outputLabel for="partdesc" value="Part Description:" style="font-weight:bold; font-size: .8em"/>
<h:outputText id="partdesc" value="#{opc.partDesc}" label="Part Description:"/>
<p:message for="partdesc" />
<h:outputText value="" />
</h:panelGrid>
</p:panel>
<p:commandButton value="Register" action="#{opc.submit()}" actionListener="#{opcD.takePartNumber}" ajax="false" icon="ui-icon-check" validateClient="true" style="margin-right:10px">
<f:attribute name="pID" value="#{opc.partID}"/>
<f:attribute name="opcDate" value="#{opc.date}"/>
<f:attribute name="opcDesc" value="#{opc.opcDesc}"/>
</p:commandButton>
</h:form>
</div>
<div style="padding-left: 500px">
<h:form style="font-size: .8em">
<p:commandButton value="Functions" action="/index?faces-redirect=true" ajax="false" icon="ui-icon-wrench"/>
</h:form>
</div>
</div>
<div style="border-bottom:2px solid #FFF">
<ui:insert name="header" >
<ui:include src="/header.xhtml" />
</ui:insert>
</div>
<div style="margin:0px 380px 0px 0px">
<h:form>
<p:panel header="Add New OPC" style="font-size: .6em">
<p:messages autoUpdate="true"/>
<h:panelGrid id="grid" columns="4" cellpadding="5">
<p:row>
<p:column colspan="10">
<h:outputLabel for="opcDate" value="Date (dd-MM-yyyy):" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDate" value="#{opc.date}" required="true" label="Date(dd-MM-yyyy):" disabled="true">
<f:convertDateTime type="date" pattern="dd-MM-yyyy"/>
</p:inputText>
<p:message for="opcDate" />
<h:outputText value="" />
<h:outputLabel for="opcDesc" value="OPC Description :" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="opcDesc" value="#{opc.opcDesc}" required="true" label="OPC Description" disabled="true"/>
<p:message for="opcDesc" />
<h:outputText value="" />
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputLabel for="partnum" value="Part Number:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="partnum" value="#{opcD.partNumber}" required="true" label="Part Number" disabled="true"/>
</p:column>
<p:column>
<h:outputLabel for="partdesc" value="Part Description:" style="font-weight:bold; font-size: .8em"/>
<p:inputText id="partdesc" value="#{opc.partDesc}" required="true" label="Part Description" disabled="true"/>
</p:column>
</p:row>
</h:panelGrid>
</p:panel>
</h:form>
</div>
<div style="padding-left: 500px">
<h:form style="font-size: .8em">
<p:commandButton value="Functions" action="/index?faces-redirect=true" ajax="false" icon="ui-icon-wrench"/>
<p:commandButton value="Submit" action="#{opcD.submitNewOPC}" ajax="false" icon="ui-icon-wrench">
<f:actionListener binding="#{opc.resetBean()}"/>
</p:commandButton>
</h:form>
</div>
</div>
<div>
<h:form id="form1">
<p:growl id="messages" showDetail="true"/>
<p:panel header="OPC Detail" style="width: 400px;font-size: .6em">
<p:panelGrid columns="2">
<h:outputLabel for="taskDesk" value="Task Description: " />
<p:inputText id="taskDesk" value="#{opcD.taskDesc}"/>
<h:outputLabel for="tasknumTime" value="Task Numinal Time: " />
<p:inputText id="tasknumTime" value="#{opcD.task_nominal_time}"/>
<f:facet name="footer">
<h:commandButton value="Register Item" action="#{opcD.addAction()}"/>
</f:facet>
</p:panelGrid>
<p:spacer height="30px;"/>
<p:dataTable value="#{opcD.opcDetailList}" var="o" widgetVar="50" style="font-size: .3em" editable="true">
<f:facet name="header">
OPC Detail List
</f:facet>
<p:ajax event="rowEdit" listener="#{opcD.onEdit}" update=":form1:messages" />
<p:ajax event="rowEditCancel" listener="#{opcD.onCancel}" update=":form1:messages" />
<p:column>
<f:facet name="header">
<h:outputText value="Task Desc" />
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.task_desc}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.task_desc}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Numinal Time" />
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{o.task_nominal_time}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{o.task_nominal_time}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="" style="width:50px">
<p:rowEditor />
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</div>
I don't fully understand what are you trying to achieve ....
But I would like to reinitialize my bean if I return again inside it.
You mean, when you navigate away from page that is driven by the bean, and than when you navigate back to it, to reinitialize the bean again?
That is what #javax.faces.ViewScoped bean is for. It keeps the data of the fields in memory as long as you are on the view. When you navigate away from it, the data is no longer available. So turn you bean into #ViewScoped.
It seems you're structuring your beans in the wrong way. For your case, you should create another backing bean for the form using #RequestScoped. Then you can inject your #SessionScoped into the #RequestScoped bean to store whatever you need into the session.

no records found in my jsf page

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}.

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

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