edit p:datatable whth String ArrayList - jsf

i have this problem: if build a p:datatable from ArrayList it's impossible editing and sometimes rowSelectd not fire.
my xhtml code:
<h:form id="form">
<p:messages id="messageWiz" showDetail="true" closable="true" autoUpdate="true"/>
<h:panelGroup>
<p:commandButton id="addPattern" icon="ui-icon-add"
actionListener="#{testController.add}" process="#this"
update="patternsId" />
<p:commandButton id="deletePattern" icon="ui-icon-delete"
actionListener="#{testController.remove}"
process="#this" update="#this, patternsId"
disabled="#{empty testController.patternsSelected}" />
</h:panelGroup>
<p:dataTable id="patternsId" var="pattern" scrollable="true" scrollHeight="200"
value="#{testController.patterns}" editable="true"
editMode="cell" widgetVar="patterns" rowIndexVar="idx"
selection="#{testController.patternsSelected}"
rowKey="#{pattern}"
emptyMessage="#{label['msg.emptytable']}" styleClass="nofooter">
<p:ajax event="rowSelect" update=":form:deletePattern" />
<p:ajax event="rowUnselect" update=":form:deletePattern" />
<p:ajax event="rowSelectCheckbox" update=":form:deletePattern"/>
<p:ajax event="toggleSelect" update=":form:deletePattern" />
<p:ajax event="rowUnselectCheckbox" update=":form:deletePattern" />
<p:ajax event="cellEdit" update=":form:messageWiz" />
<p:column selectionMode="multiple" width="20" />
<p:column>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{pattern}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{pattern}"
required="true" style="width:96%" autocomplete="off" />
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
</h:form>
controller code:
#ManagedBean
#ViewScoped
public class TestController implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<String> patterns = new ArrayList<String>();
private ArrayList<String> patternsSelected;
public ArrayList<String> getPatterns() {
return patterns;
}
public void setPatterns(ArrayList<String> patterns) {
this.patterns = patterns;
}
public ArrayList<String> getPatternsSelected() {
return patternsSelected;
}
public void setPatternsSelected(ArrayList<String> patternsSelected) {
this.patternsSelected = patternsSelected;
}
public void add() {
patterns.add(new String());
}
public void remove() {
}
}
add row and edit, then close edit end inputed vaues disappear, rowSelected not fire.

You cannot achieve this with an arraylist of strings.
You must implement a list of Pattern objects (with at least id and value members)
Backing bean (testController) must implement SelectableDataModel (unique ids will help to be sure to identify and remove the right items).

Related

p:dataTable filtered, sorted, paginated results get displayed in a single row

I'm working on a theme for an app I'm making with PrimeFaces 6.2 (community edition) and I'd like to get my simulated DAO objects working before I proceed with my css templating.
I've got an issue I came across in the past and I can't find the right answer for it again. Would someone point out an error I've made somewhere in my code?
Details:
I've made a somewhat complex DataTable using PrimeFaces LazyDataModel with little help from PrimeFaces Showcase pages. My main issue is, when I write something in the filter fields or click on any column headers to do data sorting or even click on pagination buttons I get an unexpexted data rendering issue.
Filtered, sorted and paginated results get displayed in a single concatenated row what I don't want. I've posted images and code further below for insight.
Also, I'd like to point out:
No exceptions in JS console.
No exceptions in Java console.
don't mind the missing pagination icons (text-indent: 0;)
XHTML:
<h:form id="input-form-dt2">
<H4>DATA TABLE - LAZY MODEL</H4>
<div class="flex-container">
<p:outputPanel id="dev-input-panel-13">
<p:dataTable var="DOTable" value="#{dtModelLazy.DOTList}" paginator="true" rows="10" rowKey="#{DOTable.userID}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15,25,50" selectionMode="single" selection="#{dtModelLazy.selectedObj}" id="DTModelB" lazy="true">
<p:ajax event="rowSelect" listener="#{dtModelLazy.onRowSelect}" update="input-form-dt2:dlgDTOObjDetail" oncomplete="PF('DTObjDialog').show()" />
<p:column headerText="User ID" sortBy="#{DOTable.userID}" filterBy="#{DOTable.userID}" filterMatchMode="contains">
<h:outputText value="#{DOTable.userID}" />
</p:column>
<p:column headerText="Name" sortBy="#{DOTable.name}" filterBy="#{DOTable.name}" filterMatchMode="contains">
<h:outputText value="#{DOTable.name}" />
</p:column>
<p:column headerText="Surname" sortBy="#{DOTable.surname}" filterBy="#{DOTable.surname}" filterMatchMode="contains">
<h:outputText value="#{DOTable.surname}" />
</p:column>
<p:column headerText="Age" sortBy="#{DOTable.age}" filterBy="#{DOTable.age}" filterMatchMode="contains">
<h:outputText value="#{DOTable.age}" />
</p:column>
<p:column headerText="Address" sortBy="#{DOTable.address}" filterBy="#{DOTable.address}" filterMatchMode="contains">
<h:outputText value="#{DOTable.address}" />
</p:column>
<p:column headerText="City" sortBy="#{DOTable.city}" filterBy="#{DOTable.city}" filterMatchMode="contains">
<h:outputText value="#{DOTable.city}" />
</p:column>
<p:column headerText="Post code" sortBy="#{DOTable.postCode}" filterBy="#{DOTable.postCode}" filterMatchMode="contains">
<h:outputText value="#{DOTable.postCode}" />
</p:column>
<p:column headerText="Country code" sortBy="#{DOTable.countryCode}" filterBy="#{DOTable.countryCode}" filterMatchMode="contains">
<h:outputText value="#{DOTable.countryCode}" />
</p:column>
<p:column headerText="Phone number" sortBy="#{DOTable.phoneNumber}" filterBy="#{DOTable.phoneNumber}" filterMatchMode="contains">
<h:outputText value="#{DOTable.phoneNumber}" />
</p:column>
<p:column headerText="Avatar hash" sortBy="#{DOTable.photoID}" filterBy="#{DOTable.photoID}" filterMatchMode="contains">
<h:outputText value="#{DOTable.photoID}" />
</p:column>
</p:dataTable>
<p:dialog id="dlgDTOObjDetail" header="DataTable Object Detail" widgetVar="DTObjDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="DTObjDetail">
<p:panelGrid columns="2" rendered="#{not empty dtModelLazy.selectedObj}" columnClasses="label,value">
<h:outputText value="User ID: " />
<h:outputText value="#{dtModelLazy.selectedObj.userID}" />
<h:outputText value="Name: " />
<h:outputText value="#{dtModelLazy.selectedObj.name}" />
<h:outputText value="Surname: " />
<h:outputText value="#{dtModelLazy.selectedObj.surname}" />
<h:outputText value="Age: " />
<h:outputText value="#{dtModelLazy.selectedObj.age}" />
<h:outputText value="Address: " />
<h:outputText value="#{dtModelLazy.selectedObj.address}" />
<h:outputText value="City: " />
<h:outputText value="#{dtModelLazy.selectedObj.city}" />
<h:outputText value="Post code: " />
<h:outputText value="#{dtModelLazy.selectedObj.postCode}" />
<h:outputText value="Country code: " />
<h:outputText value="#{dtModelLazy.selectedObj.countryCode}" />
<h:outputText value="Phone number: " />
<h:outputText value="#{dtModelLazy.selectedObj.phoneNumber}" />
<h:outputText value="Photo hash: " />
<h:outputText value="#{dtModelLazy.selectedObj.photoID}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</p:outputPanel>
</div>
<hr></hr>
</h:form>
LAZY MODEL:
public class DataTableModelLazy extends LazyDataModel<DODataTable> {
private static final long serialVersionUID = -2647349397077805782L;
private List<DODataTable> datasource;
public DataTableModelLazy(List<DODataTable> datasource) {
this.datasource = datasource;
}
#Override
public DODataTable getRowData(String rowKey) {
for(DODataTable dtObj : datasource) {
if(dtObj.getUserID().equals(rowKey))
return dtObj;
}
return null;
}
#Override
public Object getRowKey(DODataTable dtObj) {
return dtObj.getUserID();
}
#Override
public List<DODataTable> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
List<DODataTable> data = new ArrayList<DODataTable>();
//filter
for(DODataTable dtObj : datasource) {
boolean match = true;
if(filters != null) {
for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
Object filterValue = filters.get(filterProperty);
Field field = dtObj.getClass().getDeclaredField(filterProperty);
field.setAccessible(true);
String fieldValue = String.valueOf(field.get(dtObj));
field.setAccessible(false);
if(filterValue == null || fieldValue.startsWith(filterValue.toString())) {
match = true;
} else {
match = false;
break;
}
} catch(Exception e) {
match = false;
}
}
}
if(match) {
data.add(dtObj);
}
}
//sort
if(sortField != null) {
Collections.sort(data, new DataTableModelLazySorter(sortField, sortOrder));
}
//rowCount
int dataSize = data.size();
this.setRowCount(dataSize);
//paginate
if(dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
} catch(IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
} else {
return data;
}
}
}
VIEW BEAN:
#Named("dtModelLazy")
#ViewScoped
public class DataGeneratorBeanLazy implements Serializable {
private static final long serialVersionUID = -5918527333909822277L;
private LazyDataModel<DODataTable> DOTList;
private DODataTable selectedObj;
#Inject
private DataGeneratorBean dataGen;
#PostConstruct
public void init() {
DOTList = new DataTableModelLazy(dataGen.createDTObjects(1500));
}
public LazyDataModel<DODataTable> getDOTList() {
return DOTList;
}
public void setDOTList(LazyDataModel<DODataTable> dOTList) {
DOTList = dOTList;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("DataTable object selected!", ((DODataTable) event.getObject()).getUserID());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public DODataTable getSelectedObj() {
return selectedObj;
}
public void setSelectedObj(DODataTable selectedObj) {
this.selectedObj = selectedObj;
}
}
Update 1
I have modified the update property as update="input-form-dt2:dlgDTOObjDetail"to meet the suggestion provided. Also, I added the id property for the dialog. The issue still remains.
Update 2
I've changed my approach and started with the basic DataTable first. Also, I've stripped the .xhtml to a bare minimum. It contains only a form with the DataTable inside like so:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<div>
UI components design
</div>
<h:form id="input-form-dt1">
<h4>DATA TABLE - BASIC</h4>
<p:dataTable id="DTableA" var="dataObject" value="#{dataTableBean.objectList}" paginator="true" rows="10" rowKey="#{dataObject.id}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15,25,50">
<p:column headerText="User ID" sortBy="#{dataObject.userID}" filterBy="#{dataObject.userID}" filterMatchMode="contains">
<h:outputText value="#{dataObject.userID}" />
</p:column>
<p:column headerText="Name" sortBy="#{dataObject.name}" filterBy="#{dataObject.name}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.name}" />
</p:column>
<p:column headerText="Surname" sortBy="#{dataObject.surname}" filterBy="#{dataObject.surname}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.surname}" />
</p:column>
<p:column headerText="Age" sortBy="#{dataObject.age}" filterBy="#{dataObject.age}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.age}" />
</p:column>
<p:column headerText="Address" sortBy="#{dataObject.address}" filterBy="#{dataObject.address}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.address}" />
</p:column>
<p:column headerText="City" sortBy="#{dataObject.city}" filterBy="#{dataObject.city}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.city}" />
</p:column>
<p:column headerText="Post code" sortBy="#{dataObject.postCode}" filterBy="#{dataObject.postCode}" filterMatchMode="contains" >
<h:outputText value="#{DOTable.postCode}" />
</p:column>
<p:column headerText="Country code" sortBy="#{dataObject.countryCode}" filterBy="#{dataObject.countryCode}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.countryCode}" />
</p:column>
<p:column headerText="Phone number" sortBy="#{dataObject.phoneNumber}" filterBy="#{dataObject.phoneNumber}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.phoneNumber}" />
</p:column>
<p:column headerText="Avatar hash" sortBy="#{dataObject.photoID}" filterBy="#{dataObject.photoID}" filterMatchMode="contains">
<h:outputText value="#{dataObject.photoID}" />
</p:column>
</p:dataTable>
</h:form>
</ui:composition>
As you can see I've also removed all event listeners. I've added a new field to my data object (id of type Integer) and bound DataTables rowKey to it (previously bound to userID of type String - not a good idea). My DataTable backing bean is now as basic as it can be:
#Named("dataTableBean")
#ViewScoped
public class DataTableBean implements Serializable {
private static final long serialVersionUID = -1662465661106141910L;
private List<DTObject> objectList;
#Inject
private DataGeneratorBean dataGen;
#PostConstruct
public void init() {
setObjectList(dataGen.createDTObjects(1500));
}
public List<DTObject> getObjectList() {
if (objectList == null) {
return new ArrayList<>();
} else {
return objectList;
}
}
public void setObjectList(List<DTObject> objectList) {
this.objectList = objectList;
}
}
Now, there are no custom filters, sorters or paginators of any type, not even a data model, just raw data objects in a simple list. The output result is exactly the same as before when paginator buttons are clicked or data gets filtered. All resulting data still gets displayed in a single concatenated line.
ANSWER:
As Kukeltje pointed out in the comments I've made a complete nonsense in my main container and added an autoupdate component to it. That component messed up my data table events, loading data without a table to hold it. Once I've removed the component from my main container, everything worked out. Here is the code for my main container (commented out the troublemaker).
<div id="content-window">
<p:outputPanel id="content-panel">
<ui:include src="#{contentLoaderBean.mainContent}" />
<!-- <p:autoUpdate /> -->
</p:outputPanel>
</div>
The only situations I've seen this happening is when the datatable is fully updated in addtion to a partial update of the datatable via an event (page or filter or sort or...) In the rowSelect you do seem to update the full form which contains the datatable as well. That is bad practice and can as mentioned result in what you seem so remove that.
But...in your question there are no filter ajax events that explicitly update the full datatable so that cannot cause it. Yet with 99% vertainty there is something fully updates the datatable. Three options
there is something in your live code you left out of the datatable in your question
There is something else outside the code you posted that plays havoc (an autoupdate e.g),
an update from the server side is being done in a method

Updating row on complete of <p:ajax event="cellEdit">

I want to update cellValue in same row.
I followed the sugestions of BalusC
Updating entire <p:dataTable> on complete of <p:ajax event="cellEdit">
After all my code perform 2 Requests. The secound one makes a full page Reload and all data will reseted.
I also tried <p:remoteCommand name="updateTable" process="#this" update="kAbnrTbl" /> following this suggestion.
Using a p:remoteCommand to update a p:dataTable
Here is JSF Page:
<h:form id="kalkEditForm">
<p:outputPanel id="dropArea">
<p:remoteCommand name="updateTable" update="kAbnrTbl" />
<p:dataTable id="kAbnrTbl" value="#{tableBean.data}" var="data" editable="true" editMode="cell">
<p:ajax event="cellEdit" listener="#{tableBean.onCellEdit}" oncomplete="updateTable()"/>
<p:column headerText="Col1">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{data.col1}" /></f:facet>
<f:facet name="input"><p:inputText value="#{data.col1}" /></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Col2">
<h:outputText value="#{data.col2}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</h:form>
And here Bean:
#ManagedBean(name="tableBean")
#ViewScoped
public class TableBean {
public TableBean() {
RowData entry = new RowData("a1", "b1");
entries.add(entry);
entry = new RowData("a2", "b2");
entries.add(entry);
entry = new RowData("a3", "b3");
entries.add(entry);
}
public class RowData {
private String col1;
private String col2;
public RowData(String col1, String col2) {
this.col1 = col1;
this.col2 = col2;
}
public String getCol1() {
return col1;
}
public void setCol1(String col1) {
this.col1 = col1;
}
public String getCol2() {
return col2;
}
public void setCol2(String col2) {
this.col2 = col2;
}
}
private final ArrayList<RowData> entries = new ArrayList<RowData>();
public List<RowData> getData() {
return entries;
}
public void onCellEdit(CellEditEvent event) {
final DataTable dataTable = (DataTable)event.getComponent();
RowData data = (RowData) dataTable.getRowData();
data.setCol2("changed");
}
}
I have no idea what is wrong with the code. Why perform <p:remoteCommand ... the second Request.
Using:Primface 5.3
Back to the beginning point. If I don't use <p:remoteCommand name="updateTable" update="kAbnrTbl" /> hack, it works ok but I have to press the refreshButton.
If I use the hack I have 2 Requests and a full page reload. There must be a tiny typo or something that I overlook.
Here the code without the hack.
<h:form id="kalkEditForm">
<p:outputPanel id="dropArea">
<!-- <p:remoteCommand name="updateTable" update="kAbnrTbl" /> -->
<p:dataTable id="kAbnrTbl" value="#{tableBean.data}" var="data" editable="true" editMode="cell">
<p:ajax event="cellEdit" listener="#{tableBean.onCellEdit}" update="kAbnrTbl"/>
<!-- <p:ajax event="cellEdit" listener="#{tableBean.onCellEdit}" oncomplete="updateTable()"/> -->
<p:column headerText="Col1">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{data.col1}" /></f:facet>
<f:facet name="input"><p:inputText value="#{data.col1}" /></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Col2">
<h:outputText value="#{data.col2}" />
</p:column>
</p:dataTable>
</p:outputPanel>
<p:commandButton id="refreshButton" value="Redisplay" update="kAbnrTbl" />
</h:form>
I used event="rowEdit", this worked for me.
<p:ajax event="rowEdit" listener="#{tableBean.onCellEdit}" oncomplete="updateTable()" />
Following the note from user3821232, the workaround is to be used instead of "celleditor" "inplace" in conjunction with a standard <p:ajax.. call.
Here you can see the workaround.
xthml:
<h:form id="kalkEditForm">
<p:outputPanel id="dropArea">
<p:dataTable id="kAbnrTbl" value="#{tableBean.data}" var="data" editable="true" editMode="cell" rowIndexVar="row">
<p:column headerText="Col1" id="col1" sortBy="#{data.col1}" sortable="true">
<p:inplace>
<f:facet name="output"><h:outputText value="#{data.col1}" /></f:facet>
<f:facet name="input">
<p:inputText value="#{data.col1}" >
<p:ajax event="blur" process="#this" listener="#{tableBean.updateData(row, 'col1')}" update="kAbnrTbl"/>
</p:inputText>
</f:facet>
</p:inplace>
</p:column>
<p:column headerText="Col2">
<h:outputText id="col2" value="#{data.col2}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</h:form>
Bean:
#ManagedBean(name="tableBean")
#ViewScoped
public class TableBean {
private static final Logger logger = Logger.getLogger(TableBean.class);
public TableBean() {
RowData entry = new RowData("a1", "b1");
entries.add(entry);
entry = new RowData("a2", "b2");
entries.add(entry);
entry = new RowData("a3", "b3");
entries.add(entry);
}
public class RowData {
private String col1;
private String col2;
public RowData(String col1, String col2) {
this.col1 = col1;
this.col2 = col2;
}
public String getCol1() {
return col1;
}
public void setCol1(String col1) {
this.col1 = col1;
}
public String getCol2() {
return col2;
}
public void setCol2(String col2) {
this.col2 = col2;
}
}
private final ArrayList<RowData> entries = new ArrayList<RowData>();
public List<RowData> getData() {
return entries;
}
public void updateData(Integer row, String colName){
logger.debug(String.format("updateData called row:%d colName %s", row, colName));
RowData data = getData().get(row);
data.setCol2("changed");
}
}

Update a row in p:dataTable

I'm working with JSF and primefaces. I want to update a row when I click on the button (pencil). I used the first code from this tutorial (Primefaces docs), but dosent work in my case.
the problem is : when i click the button (pencil) to update a row, nothing change. i have always the old values
This is my JSF code :
<f:view>
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
<p:dataTable id="tservice" var="item" value="#{serviceMBean.services}" editable="true" style="margin-bottom:20px">
<f:facet name="header"> edit </f:facet>
<p:ajax event="rowEdit" listener="#{serviceMBean.onRowEdit}" update=":form:msgs" />
<p:ajax event="rowEditCancel" listener="#{serviceMBean.onRowCancel}" update=":form:msgs" />
<p:column headerText="Libelle du service">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{item.libelleservice}" /></f:facet>
<f:facet name="input">
<p:inputText value="#{item.libelleservice}" style="width:100%" label="Libelle"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Utilisateurs/Service">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{item.nbruserservice}" /></f:facet>
<f:facet name="input">
<p:inputText value="#{item.nbruserservice}" style="width:100%" label="Nbre Users"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
And this is my managed bean code:
#Named(value = "serviceMBean")
#ViewScoped
public class ServiceMBean implements Serializable {
private List<Service> serviceList;
private Service s;
#EJB
private ServiceManager serviceManager;
public ServiceMBean() {}
public void modifierService(Service s1) {
this.serviceManager.updateService(s1);
}
public void onRowEdit(RowEditEvent event) {
Service s2 = (Service) event.getObject();
System.out.println("--->" + s2.getNbruserservice());
FacesMessage msg = new FacesMessage("Service Modifié", ((Service) event.getObject()).getLibelleservice());
this.modifierService(s2);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Modification annulée", ((Service) event.getObject()).getLibelleservice());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
And this is my code for ServiceManager:
public void updateService(Object service) {
em.merge(service);
}
I think the setter in my JSF page doesn't work. Any solutions or suggestions?
Solution : Add a void method with #PostConstruct.
Example : #PostConstruct
#PostConstruct
public void initialiser() {
serviceList = this.getServices();
}
Don't forget the getter and setter of serviceList
In the JSF page, the value of datatable will be : value="#{ServiceMBean.serviceList}"

JSF Primefaces datatable in cell editMode not sending the edited value to the managed bean

I have two primefaces dataTables. The first show the instances of a MainEntity.
The second one show a list of Words (just strings) associated with the selected MainEntity on the first datatable.
The printscreen illustrates what I mean.
My problem is, when I edit a string on the Word List, my listener method won't receive the new value. In fact, when I call the event.getNewValue() method, I get old value.
What am I missing?
I'm using JavaServer Faces 2.2, Primefaces 5.0 and Spring Framework 4.0.3.
Thanks in advance for any help.
The code for the xhtml, the managed bean and the MainEntity are as follows:
mainEntity.xhtml:
<h:body>
<h:form id="mainEntityForm">
<p:panelGrid columns="1" fullPage="true" id="dashboard">
<f:facet name="header">
<h2>MainEntity Table</h2>
</f:facet>
<p:panel>
<f:facet name="header">
MainEntity List
<p:commandButton value="New MainEntity"
actionListener="#{mainEntityController.createMainEntityDialog}"
styleClass="header-button">
<p:ajax event="dialogReturn" update=":mainEntityForm:mainEntityTable" />
</p:commandButton>
</f:facet>
<p:dataTable id="mainEntityTable" var="mainEntity" value="#{mainEntityController.mainEntities}"
editable="true" editMode="cell" widgetVar="cellMainEntity"
selectionMode="single" selection="#{mainEntityController.selectedMainEntity}"
rowKey="#{mainEntity.id}" tableStyle="width:auto">
<p:ajax event="rowSelect" update=":mainEntityForm:stringGrid :mainEntityForm:entityAGrid :mainEntityForm:entityBGrid" />
<p:ajax event="cellEdit" listener="#{mainEntityController.onEditMainEntity}" update=":mainEntityForm:mainEntityTable" />
<p:column headerText="ID">
<h:outputText value="#{mainEntity.id}" />
</p:column>
<p:column headerText="Name">
<p:cellEditor>
<f:facet name="output">
<h:outputText id="nameOutput" value="#{mainEntity.name}" />
</f:facet>
<f:facet name="input">
<h:inputText id="atyInput" value="#{mainEntity.qty}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Commands">
<p:commandButton title="Remove MainEntity" icon="ui-icon-trash"
actionListener="#{mainEntityController.deleteMainEntity(mainEntity)}"
update=":mainEntityForm:mainEntityTable" />
</p:column>
</p:dataTable>
</p:panel>
<p:panelGrid fullPage="true" id="mainEntityDetail">
<f:facet name="header">
<p:row>
<p:column colspan="4">
<h2>MainEntity Detail</h2>
</p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<p:panel>
<f:facet name="header">
Word List
<p:commandButton value="New Word"
actionListener="#{mainEntityController.addNewWord()}"
styleClass="header-button"
update=":mainEntityForm:wordGrid">
</p:commandButton>
</f:facet>
<p:dataTable id="wordGrid" var="word"
value="#{mainEntityController.selectedMainEntity.wordList}"
tableStyle="width:auto" editable="true" editMode="cell" widgetVar="cellWord">
<p:ajax event="cellEdit" listener="#{mainEntityController.onEditWord}" />
<p:column headerText="Word">
<p:cellEditor>
<f:facet name="output">
<h:outputText id="wordOutput" value="#{word}" />
</f:facet>
<f:facet name="input">
<h:inputText id="wordInput" value="#{word}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Commands">
<p:commandButton title="Remove Word"
icon="ui-icon-trash"
actionListener="#{mainEntityController.removeWord(word)}"
update=":mainEntityForm:wordGrid" />
</p:column>
</p:dataTable>
</p:panel>
</p:column>
</p:row>
</p:panelGrid>
</p:panelGrid>
</h:form>
</h:body>
MainEntityController.java (managed bean):
#ManagedBean
#SessionScoped
public class MainEntityController {
//...
private MainEntity selectedMainEntity;
public List<MainEntity> mainEntities;
//...
public MainEntity getSelectedMainEntity(){
return selectedMainEntity;
}
public void setSelectedMainEntity(MainEntity mainEntity){
this.selectedMainEntity = mainEntity;
}
//...
public void onEditWord(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue)) {
// THE PROBLEM IS HERE
// I NEVER ACTUALLY REACH THIS CODE
// newValue is always equal to oldValue!
FacesContext context = FacesContext.getCurrentInstance();
String word = context.getApplication().evaluateExpressionGet(context, "#{word}", String.class);
System.out.println(newValue);
System.out.println(word);
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Word Changed", "Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
MainEntity.java:
#Entity
public class MainEntity {
#Id
private String id;
#ElementCollection(fetch=FetchType.EAGER)
#CollectionTable(
name="MainEntity_Word",
joinColumns = #JoinColumn(name = "id", referencedColumnName="id")
)
#Column(name = "word")
private Set<String> wordList;
//...
public void addWord(String word) {
this.wordList.add(word);
}
public void removeWord(String word) {
this.wordList.remove(word);
}
public Set<String> getWordList() {
return wordList;
}
public void setWordList(Set<String> wordList) {
this.wordList = wordList;
}
}
Change
<h:inputText id="wordInput" value="#{word}" />
to
<p:inputText id="wordInput" value="#{word}" />
or
<h:inputText id="wordInput" value="#{word}" >
<p:ajax event="change" process="#this"/>
</h:inputText>
You need to ajaxify the input component, and at last update the outputText component.
Edited:
change this column :
<p:column headerText="Word" >
<p:cellEditor>
<f:facet name="output">
<h:outputText id="wordOutput" value="#{word}" />
</f:facet>
<f:facet name="input">
<h:inputText id="wordInput" value="#{word}" />
</f:facet>
</p:cellEditor>
</p:column>
to
<p:column headerText="Word" >
<p:cellEditor>
<f:facet name="output">
<h:outputText id="wordOutput" value="#{word}" />
</f:facet>
<f:facet name="input">
<p:inputText id="wordInput" value="#{word}" >
<p:ajax event="change" update="wordOutput" />
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
Edit 2 :
From Chapter 24 Introduction to the Java Persistence API
If an entity instance be passed by value as a detached object, such as
through a session bean’s remote business interface, the class must
implement the Serializable interface.
I finally got it working.
I suspected of the String immutable nature and what I did was to encapsulate the 'word' in a class like the following:
public class Word {
private String word;
Word (String word) {
this.setWord(word);
}
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
}
After that, I also had to create a set inside the managed bean (controller) to hold the set of words, like 'private Set managedWordList;'.
I also changed the getter for the list, inside the managed bean, to convert from the String set to a Word set like:
public Set<Word> getWordList() {
if (this.selectedMainEntity != null){
this.wordList = new HashSet<Word>();
for (String word : this.selectedMainEntity.getWordList()) {
this.wordList.add(new Word(word));
}
}
return this.wordList;
}
Finally, I changed the dataTable to reference the new set. From:
<p:dataTable ... value="#{mainEntityController.selectedMainEntity.wordList}"... />
To:
<p:dataTable ... value="#{mainEntityController.wordList}"... />
And only then I got it to work as I expected.

JSF - PrimeFaces , How to get the value of a booleanCheckbox / booleanButton in a list

I have a jsf page that I can't update the value of some checkboxes in a list of userDamain objects, in fact this is a part of my jsf page :
<h:outputText value="USER's rights list: "></h:outputText>
<p:dataTable id="userss" var="userr" value="#{userMB.userListe}">
<p:column>
<f:facet name="header"><h:outputText value="FirstName" /></f:facet>
<h:outputText value="#{userr.firstName}" />
</p:column>
<p:column>
<h:panelGrid columns="1" style="margin-bottom:10px" cellpadding="5">
<h:outputText value="Basic Usage: " />
<p:selectBooleanCheckbox value="#{userr.deletee}" immediate="true" actionListener="#{userr.deletee}" />
</h:panelGrid>
<p:commandButton value="Submit" update="display" oncomplete="dlg.show()" />
<p:dialog header="Selected Values" modal="true" showEffect="fade" hideEffect="fade" widgetVar="dlg">
<h:panelGrid columns="1" id="display">
<h:outputText value="Value 1: #{userr.deletee}" />
</h:panelGrid>
</p:dialog>
</p:column>
when I click on the boolean button 'Submit', the value of the userr.deletee is always false ( the default value ) and it's not updated anyway, I tried to use the Listner and actionListener in the booleanButton but it doesn't work, I also tried the postValidate event, so if someone has any idea of that, I would be graceful.
this is a part of my managed bean:
private List<UserDomain> userListe ;
public List<UserDomain> getUserListe() {
return this.userListe;
}
public void loadUserListe(){
this.userListe = new ArrayList<UserDomain>();
this.userListe.addAll(getUserServicee().getAll());
}
public void setUserListe(List<UserDomain> userListe) {
this.userListe = userListe;
}
a part of the userDomain bean:
...
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Transient
private boolean deletee;
public boolean isDeletee() {
return deletee;
}
public void setDeletee(boolean deletee) {
this.deletee = deletee;
}
I found out a solution which seems logic to me, I added to my checkbox an ajax behavior to execute a method and an attribute which called in this method to get the whole userDomain object, so on I can get the user.deletee value, here is a part of the code I m talking about:
<h:panelGrid columns="1" style="margin-bottom:10px" cellpadding="5">
<h:outputText value="Delete Right: " />
<p:selectBooleanCheckbox value="#{userr.deletee}">
<f:ajax execute="#this" listener="#{userMB.saveUserRights}" />
<f:attribute name="user" value="#{userr}" />
</p:selectBooleanCheckbox>
</h:panelGrid>
I hope this will be helpful for you

Resources