How to iterate a HashMap with primefaces selectable datatable - jsf-2

I have tried different solutions but none is working in my case. I want all the rows in this datatable to be selectable. The problem seems to be the <ui:repeatthat is probably overriding the objects...
My bean:
#ManagedBean
#ViewScoped
public class Chat {
private static Map<String, List<ChatObject>> chat = new LinkedHashMap<String, List<ChatObject>>();
private ChatObject selectedChatObject;
public void onChatRowSelection(){
if(getSelectedChatObject() != null){
System.out.println("test");
}
}
public List<Map.Entry<String, List<ChatObject>>> getChatList() {
Set<Map.Entry<String, List<ChatObject>>> productSet = chat.entrySet();
return new ArrayList<Map.Entry<String, List<ChatObject>>>(productSet);
}
#PostConstruct
public void postConstructMethod() {
if(chat.isEmpty()){
List<ChatObject> objectsList1 = new ArrayList<ChatObject>();
objectsList1.add(new ChatObject("3369818", "1", "1"));
objectsList1.add(new ChatObject("3369819", "2", "2"));
objectsList1.add(new ChatObject("3369820", "3", "3"));
chat.put("Chat Topic 1", objectsList1);
List<ChatObject> objectsList2 = new ArrayList<ChatObject>();
objectsList2.add(new ChatObject("3369813", "4", "4"));
objectsList2.add(new ChatObject("3369815", "5", "5"));
chat.put("Chat Topic 2", objectsList2);
}
}
public ChatObject getSelectedChatObject() {
return selectedChatObject;
}
public void setSelectedChatObject(ChatObject selectedChatObject) {
this.selectedChatObject = selectedChatObject;
}
}
My JSF:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:fn="http://java.sun.com/jsp/jstl/functions">
<h:form id="form" enctype="multipart/form-data" acceptcharset="ISO-8859-1">
<ui:repeat value="#{chat.chatList}" var="chatEntry">
<h2><h:outputText value="#{chatEntry.key}" /></h2>
<br />
<p:dataTable
value="#{chatEntry.value}"
var="chatEntryVar"
widgetVar="chatTableWV"
styleClass="geralBorderless"
style="cursor:pointer"
rowKey="#{chatEntryVar.id}"
rendered="true"
selectionMode="single"
selection="#{chat.selectedChatObject}"
paginatorAlwaysVisible="false">
<p:ajax event="rowSelect"
listener="#{chat.onChatRowSelection}"
oncomplete="chatTableWV.unselectAllRows();">
</p:ajax>
<p:column>
<h:outputText value="#{chatEntryVar.name}" />
</p:column>
</p:dataTable>
</ui:repeat>
</h:form>
</html>
All the 5 ChatObject in my Map are successfully shown in my page. But onChatRowSelection method will only print "test" when I click in the rows related to the second list I added to my map: objectList2. When I click in the lines from the first list I added objectList1, when the system enters in the onChatRowSelection method, selectedChatObject will be null. How can I fix this?

Your problem is here:
<ui:repeat ...>
<p:dataTable ... widgetVar="chatTableWV">
<p:ajax ... oncomplete="chatTableWV.unselectAllRows();">
Multiple data tables are been assigned exactly the same widgetVar name in JavaScript scope. In effects, the following JavaScript code is generated:
window['chatTableWV'] = new Widget(tableElement1);
window['chatTableWV'] = new Widget(tableElement2);
window['chatTableWV'] = new Widget(tableElement3);
// ...
Basically, every iteration overrides the last object assigned to the declared widgetVar name until it ends up referencing the last one. All widgets expect of the last one are basically unavailable, causing them to not be functional anymore as to row selection.
Fix it accordingly by giving them each an unique widgetVar. You could use the iteration index of <ui:repeat> for this.
<ui:repeat ... varStatus="loop">
<p:dataTable ... widgetVar="chatTableWV_#{loop.index}">
<p:ajax ... oncomplete="chatTableWV_#{loop.index}.unselectAllRows();">
This way the following JavaScript code is generated:
window['chatTableWV_0'] = new Widget(tableElement1);
window['chatTableWV_1'] = new Widget(tableElement2);
window['chatTableWV_2'] = new Widget(tableElement3);
// ...
And finally PrimeFaces widget manager can find them all.

Related

update component in another xhtml form from Custom layout p:selectOneRadio not working

My xhtml is split in to Menu area (defaultMenu.xhtml) and Content area (defaultContent.xhtml).
The code for defaultMenu.xhtml is:
<h:form id="defaultmenuform">
<p:outputPanel id="menupanel" class="contain auto-fixed-center">
<p:panel id="pmenu" visible="#{phController.user.menuVisible}">
<table id="stutable">
<tr>
<td width="15%">
<p:outputLabel id="stuname" value="#{phController.phBean.studentName}" />
</td>
<td>
<p:tabMenu activeIndex="#{param.selectedtab}">
<p:menuitem value="Home" outcome="phome" icon="ui-icon-star">
<f:param name="selectedtab" value="0" />
</p:menuitem>
<p:menuitem value="Bank" outcome="bhome" icon="ui-icon-person">
<f:param name="selectedtab" value="1" />
</p:menuitem>
</p:tabMenu>
</td>
</tr>
</table>
</p:panel>
</p:outputPanel>
</h:form>
The defaultContent.xhtml actually displays the ph.xhtml content (as part of functional navigation) and the code is:
<ui:define name="content">
<f:event listener="#{phController.readPeople}" type="preRenderView">
</f:event>
<h:form id="form">
<p:selectOneRadio id="selstud" value="#{phController.phBean.ssSeq}" layout="custom">
<p:ajax update=":defaultmenuform:parentmenupanel :defaultmenuform:stuname" listener="#{phController.onChangePerson}"/>
<f:selectItems value="#{phController.selectStudents}" />
</p:selectOneRadio>
<div style="width: 300px; float:left;">
<p:dataGrid var="studentlist" value="#{phController.listStudent}" columns="1" rowIndexVar="stuindex">
<p:panel header="" style="text-align:left">
<h:panelGrid columns="1" style="width:100%">
<h:outputText value="#{studentlist.studentName}" />
<p:radioButton for=":form:selstud" itemIndex="#{stuindex}"/> Select
</h:panelGrid>
</p:panel>
</p:dataGrid>
</div>
</h:form>
</ui:define>
The code for backing bean is:
Map<String, Object> studentparam = new HashMap<>();
studentparam.put("studentSeq", phBean.getSsSeq());
lS = getBaseDAOService().readStudent("readStudent", studentparam);
phBean.setStudentName(lS.get(0).getStudentFirstName() + " " + lS.get(0).getStudentLastName());
As you can see, I am calling the onChangeStu method to display the selected Student Name in defaultMenu.xhtml. I am using Custom Layout p:selectOneRadio in ph.xhtml and onClick trying to update a p:outputLabel in defaultMenu.xhtml.
The backing bean method gets invoked successfully and the value is also set in variable phController.phBean.studentName, but the update is not working. I also checked using view source and the id is “:defaultmenuform:stuname”, I also tried updating the menu panel ":defaultmenuform:menupanel”, but none of this works.
Not sure how to resolve this. Please suggest.
Including the structure of all .xhtmls
<h:body id="entirePageBody">
<div id="page">
<ui:insert name="header" >
<ui:include src="/template/defaultHeader.xhtml" />
</ui:insert>
<ui:insert name="menu" >
<ui:include src="/template/defaultMenu.xhtml" />
</ui:insert>
<div id="content_div" class="auto-fixed-center">
<div id="content_div_padding" class="content-block">
<ui:insert name="content" >
<ui:include src="/template/defaultContent.xhtml" />
<ui:debug hotkey="z" />
</ui:insert>
</div>
</div>
<ui:insert name="footer" >
<ui:include src="/template/defaultFooter.xhtml" />
</ui:insert>
</div>
</h:body>
PhController.java:
public class PhController extends BaseController implements Serializable {
private List<Stud> listStudent;
private List selectStudents;
SelectItem option;
private PhBean phBean;
private Boolean menuVisible;
int counter = 0;
public PhController() {
phBean = new PhBean();
}
public void readPeople() {
listStudent = new ArrayList<Stud>();
listStudent.add(new Stud(1, "John Miller"));
listStudent.add(new Stud(2, "Scott Jackson"));
selectStudents = new ArrayList();
option = new SelectItem(listStudent.get(0).getStudentSeq(), "Select");
selectStudents.add(option);
option = new SelectItem(listStudent.get(1).getStudentSeq(), "Select");
selectStudents.add(option);
phBean.setSsSeq(String.valueOf(1));
phBean.setSelectedName(listStudent.get(0).getStudentName());
menuVisible = true;
}
public void onChangePerson() {
phBean.setSelectedName(listStudent.get(1).getStudentName());
}
// Getters and Setters
}
PhBean.java:
public class PhBean implements Serializable {
private String ssSeq;
private String studName; // Used to display the name in the Menu bar.
private String selectedName;
public PhBean() {
}
// Getters and Setters
}
I'd say that in the p:ajax in defaultContent.xhtml the list of components to be updated should be separated with spaces only, no commas - so try changing this:
update=":defaultmenuform:menupanel, :defaultmenuform:stuname"
to this:
update=":defaultmenuform:menupanel :defaultmenuform:stuname"
UPDATE
I played with this a bit more and may have found a clue - please add the following code to defaultmenuform:
<p:messages autoUpdate="true" showDetail="true" />
This should help us tracking the reason for failed validation (in case failing validation is the root cause for you - as I said, I have rather limited possibility to reproduce this issue).
Anyway, when I selected some item in p:selectOneRadio, an error message like this appeared:
Conversion Error setting value 'test001.Student#4110c95c' for 'null Converter'.
And the root cause was on this row:
<p:selectOneRadio id="selstud" value="#{phController.phBean.ssSeq}" layout="custom">
p:selectOneRadio expects only String to be passed as a value - and ssSeq is very likely of a different type. Try to change the way value is populated to ensure it is always String - maybe a different attribute of the phBean or simply a brand new String one.
NOTE: if this doesn't help, maybe you could update your question with very simplified example of how phController and phBean could look like if we are to test it.
UPDATE #2
So you have explained there is a problem that you want to call phController.readPeople every time the page is loaded/refreshed, but instead it gets loaded with each and every Ajax request, thus overwriting the values.
In your PhController (it is a bean, right? session scoped?) you could add something like this (omitted null checks for the sake of readability):
public void readPeopleOnGet() {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletRequest req = (HttpServletRequest) ec.getRequest();
String reqMethod = req.getMethod();
if ("GET".equals(reqMethod)) {
readPeople();
}
}
With the above method you could keep this part of your defaultContext.xhtml in place, provided it is actually called (I assume so), just with the listener method changed:
<f:event listener="#{phController.readPeopleOnGet}" type="preRenderView">
</f:event>
The method readPeopleOnGet will still be called with every request to the page, but since Ajax requests are POST, it will only call readPeople when the page is loaded or refreshed as whole.
This may not be a "perfectly clean" solution, but seemed to work properly when I tested it.
UPDATE #3
Well, since you use PrimeFaces, it would be possible to identify Ajax call also this way:
public void readPeopleOnGet() {
RequestContext rc = RequestContext.getCurrentInstance();
if (!rc.isAjaxRequest()) {
readPeople();
}
}
But if I got your point from latest comments, you want to only run readPeople when the page is loaded for the very first time - so the following part could be even better for that.
You didn't answer if PhController is actually a bean, but I assume it is (there were no annotations visible from the code you posted). You may try making it #SessionScoped:
#ManagedBean
#SessionScoped
public class PhController extends BaseController implements Serializable {
// the rest of the PhController goes here...
Then you could add something like this to the PhController:
#PostConstruct
private void init() {
readPeople();
}
The annotation #PostConstruct ensures the method init is called exactly once after the bean was created. You can continue calling the method readPeople from other places as necessary, while removing both the <f:event ... /> and readPeopleOnGet as these will no longer be needed.

JSF El expression retaining old value (JSF life cycle)

I have create a test project with JSF2.0 and richfaces. I am trying to plot chart. Now, I got value from database to bean and to datatable. Now when I wanted to pass this value to javascript varible and found this answer from The BalusC very userful. It works fine but the value that javascript variable gets after oncomplete="jsonDemo('#{kpilist.json}')". i.e. the value of #{kpilist.json} is not up-to-date it's last one.
I have printed the value of #{kpilist.json}. If it's printed afer datatabe the value is current. If it's printed before datatable it's last value. Any way since oncomplete attribute of a4j:ajax executes after eveything is completed why doesn't #{kpilist.json} show latest value? What is the order of execution of various listener and oncomplete attributes of richfaces and jsf component?
My Managed Bean:
#ManagedBean(name = "kpilist")
#ViewScoped
public class KPIListController implements Serializable {
private static final long serialVersionUID = 1L;
boolean state = true;
String selectedKPIType;
String selectKPITime = "D";
boolean renderDatatable;
String json;
public String getJson() {
return json;
}
public boolean isRenderDatatable() {
return renderDatatable;
}
public void setRenderDatatable(boolean renderDatatable) {
this.renderDatatable = renderDatatable;
}
public boolean isState() {
return state;
}
public List<String> showViewList() {
Logger.getLogger(KPIListController.class.getName()).warning("Show view List:");
KPIDAO kpiDAO = new KPIDAO();
try {
Logger.getLogger(KPIListController.class.getName()).info("Into show view List ---select One");
return kpiDAO.showViewList(selectKPITime);
} catch (SQLException ex) {
ex.printStackTrace();
Logger.getLogger(KPIListController.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public void setState(boolean state) {
this.state = state;
}
public String getSelectedKPIType() {
return selectedKPIType;
}
public void setSelectedKPIType(String selectedKPIType) {
this.selectedKPIType = selectedKPIType;
}
public String getSelectKPITime() {
return selectKPITime;
}
public void setSelectKPITime(String selectKPITime) {
this.selectKPITime = selectKPITime;
}
public List<KPI> getKPI() {
Logger.getLogger(KPIListController.class.getName()).warning("Get KPI Values:");
KPIDAO kpiDAO = new KPIDAO();
List<KPI> kpiList = new ArrayList<KPI>();
try {
kpiList = kpiDAO.getKPI(selectedKPIType);
Logger.getLogger(KPIListController.class.getName()).warning("KPI List:"+kpiList.size());
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
Gson gson = new Gson();
json= gson.toJson(kpiList);
return kpiList;
}
public void resetFormValues() {
Logger.getLogger(KPIListController.class.getName()).warning("Reset form:");
selectedKPIType = "--";
}
}
My View:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
</h:head>
<h:body>
<ui:composition template="/contentTemplate.xhtml">
<ui:define name="windowTitle">KPI Index</ui:define>
<ui:define name="content" >
<h:outputScript name="js/graphics/jquery.js"/>
<h:outputStylesheet name="/css/jquery-ui-1.8.22.custom.css"/>
<h:outputScript name="js/graphics/jquery-ui-1.8.22.custom.min.js"/>
<h:outputScript name="js/OpenLayers/OpenLayers.js"/>
<h:outputScript name="js/graphics/raphael-min.js"/>
<h:outputScript name="js/graphics/canvg.js"/>
<h:outputScript name="js/graphics/paths.js"/>
<h:outputScript name="js/graphics/draw.js"/>
<h:form id="ins_sel_form">
<h:outputText value="KPI TIME FRAME"/>
<h:selectOneRadio value="#{kpilist.selectKPITime}" >
<f:selectItem itemLabel="DAILY" itemValue="D" />
<f:selectItem itemLabel="WEEKLY" itemValue="W" />
<f:selectItem itemLabel="LAST WEEK" itemValue="LW" />
<a4j:ajax event="change" render="ins_sel_form:selectOnemenu dataPnl" listener="#{kpilist.resetFormValues()}" />
</h:selectOneRadio>
<h:outputText value="Major KPI Type"/>
<h:selectOneMenu id="selectOnemenu" value="#{kpilist.selectedKPIType}" >
<f:selectItem itemValue="--" itemLabel="--"></f:selectItem>
<f:selectItems itemValue="#{item.toString()}" var="item" itemLabel="#{item.toString()}" value="#{kpilist.showViewList()}"/>
<a4j:ajax event="change" render="dataPnl" oncomplete="jsonDemo('#{kpilist.json}')" />
</h:selectOneMenu>
<h:outputText value="Show / Hide Map"/>
</h:form>
<rich:panel id ="dataPnl">
<rich:dataTable id="kpiValueTable" value="#{kpilist.KPI}" var="kpi" style="width:100%" rows="20" rendered="#{kpilist.selectedKPIType!=null and kpilist.selectedKPIType !='--' }" >
<rich:column>
<f:facet name="header" >
<h:outputText value ="Value"></h:outputText>
</f:facet>
<h:outputText value="#{kpi.KPIValue}"></h:outputText>
</rich:column>
</rich:dataTable>
JSON String : <h:outputText id="json" value ="#{kpilist.json}"/>
<center><rich:dataScroller for="kpiValueTable" rendered="#{kpilist.selectedKPIType!=null and kpilist.selectedKPIType!='--'}"/></center>
</rich:panel>
<rich:panel id="map" style="display: none;">
</rich:panel>
</ui:define>
</ui:composition>
</h:body>
</html>
Javascript:
function jsonDemo(jsonString){
console.log("Chart data already retrieved: " + jsonString);
var data = $.parseJSON(jsonString);
$.each(data,function(i,val){
console.log("The value of i: "+i+" The val: "+val.NCELLCLUSTER);
});
}
The EL expression in your oncomplete is evaluated at the moment the HTML/JS code is generated by JSF (thus, on the initial HTTP request). It's not evaluated at the moment the oncomplete is executed in JS as you seem to expect. It's not the webbrowser who evaluates EL expressions, it's the webserver. The oncomplete is by the way just executed after render. With a HTTP traffic debugger and a JS debugger (press F12 in Chrome/IE9/Firebug) you can easily track it.
There are several possibilities to solve this:
Just invoke a $.get() or $.getJSON() in jQuery and do the job in a normal servlet instead, or better, a JAX-RS webservice.
function jsonDemo() {
$.getJSON("servletURL", function(jsonData) {
// ...
});
}
Replace the oncomplete by some <h:outputScript> which you render/update by ajax.
<a4j:ajax ... render="json" />
...
<h:panelGroup id="json">
<h:outputScript rendered="#{not empty bean.json}">jsonDemo(#{bean.json});</h:outputScript>
</h:panelGroup>
Unrelated to the concrete problem, you've there by the way a conceptual mistake as to passing around JSON data. You're stringifying it while passing as argument like so jsonDemo('#{kpilist.json}') and then you're parsing the JSON afterwards using $.parseJSON(). This makes no sense. Remove those singlequotes around the argument like so jsonDemo(#{kpilist.json}) and then you don't need that $.parseJSON() line anymore. The data is then already in JSON format.
Try changing from a4j:ajax to f:ajax
not sure if a4j:ajax works with plain JSF components

SelectBooleanCheckbox rendered state does not match the backing bean

I'm using JSF2.0 and am building up a wizard. I have encountered a problem with SelectBooleanCheckboxes. Here is the workflow:
Load page with checkboxes (values are bound to a SortedMap in the backing bean).
Tick them, and click next. This increments a cursor, which the page uses to determine which PanelGroup the load.
The (correct) values are persisted to the bean.
Click back (cursor is decremented) and page renders the editable checkboxes. The first checkbox is not ticked (even though the bound variable holds a value of true for that box).
This cursor-based approach (which contains all of the wizard screens) doesn't seem to work. However, if i slightly modify this so that the prev/next buttons bring up different xhtml pages, this issue disappears.
Unfortunately I cant do this. We are going to plug this wizard into a modal dialog, so visiting a new page on prev/next will not work
I've written up a smallish example of this (rather than asking you to wade through the entire wizard).
Here is the Java class:
#ConversationScoped
#Named("hashBool")
public class HashBoolTest2 implements Serializable {
private static final long serialVersionUID = 1962031429874426411L;
#Inject private Conversation conversation;
private List<RestrictionItem> list;
private SortedMap<String, Boolean> values;
private int cursor;
public HashBoolTest2( ) {
List<String> none = new ArrayList<String>();
none.add("");
this.setList( new ArrayList< RestrictionItem >( ) );
this.getList().add( new RestrictionItem( "a", "a", none ) );
...
this.getList().add( new RestrictionItem( "e", "e", none ) );
this.setValues( new TreeMap< String, Boolean >() );
this.setCursor( 0 );
}
#PostConstruct
public void andThis() {
this.conversation.begin( );
}
// getters and setters for instance variables
#Override
public String toString() {
return "Values : " + this.values.toString( ) + " List: " + this.list.toString( );
}
public void kill() {
this.conversation.end( );
}
public void doNext(ActionEvent e) {
this.cursor++;
}
public void doPrev(ActionEvent e) {
this.cursor--;
}
}
Here is the XHTML fragment:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>IGNORED</title>
</head>
<body>
<ui:composition>
<h:panelGroup id="container">
<h:form>
<!-- edit state -->
<h:panelGroup id="edit" rendered="#{hashBool.cursor eq 0}">
<code>
<h:outputText value="#{hashBool.toString()}" escape="false"/>
</code>
<ul>
<ui:repeat value="#{hashBool.list}" var="elem">
<li>
<h:selectBooleanCheckbox id="elem" value="#{hashBool.values[elem.id]}" title="#{elem.displayName}" />
<h:outputLabel for="elem" value="#{elem.displayName}"/>
</li>
</ui:repeat>
</ul>
</h:panelGroup>
<!-- view state -->
<h:panelGroup id="view" rendered="#{hashBool.cursor eq 1}">
<code>
<h:outputText value="#{hashBool.toString()}" escape="false"/>
</code>
</h:panelGroup>
<br/>
<!-- buttons -->
<h:panelGroup id="buttons">
<f:ajax render=":container">
<h:commandButton value="Prev" actionListener="#{hashBool.doPrev}"/>
<h:commandButton value="Next" actionListener="#{hashBool.doNext}"/>
</f:ajax>
<h:commandButton value="Kill" actionListener="#{hashBool.kill()}"/>
</h:panelGroup>
</h:form>
</h:panelGroup>
</ui:composition>
</body>
</html>
Any suggestions are welcome! (And sorry if this is a double post, i havnt been able to uncover anything similar while searching here)
Mainly to ensure that the Wisdom of the Ancients remains properly documented (http://xkcd.com/979/): Turns out this is a bug within JSF 2.0.2 (which comes bundled with Liferay 6.0 GA 4). See here for more info: http://java.net/jira/browse/JAVASERVERFACES-1561

PrimeFaces 3.0.M3 Cell Editor does not update value

I have read there, but i can't take edited value from primefaces datatable cellEditor, it gives me unedited value. i am using jpa.
xhtml page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui"
template="/templates/masterLayout.xhtml">
<ui:define name="windowTitle">
learn
</ui:define>
<ui:define name="content">
<h:form>
<p:dataTable value="#{lesson.lessonValue}" var="l" style="width: 400px">
<p:ajax event="rowEdit" listener="#{lesson.onEditRow}"/>
<p:column headerText="Lessons" style="width: 300px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{l.lessonName}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{l.lessonName}" style="width: 100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Options">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
lesson.java:
public class lesson implements Serializable {
private String name;
protected EntityLesson[] lessonList;
public String getName() { return name; }
public void setName(String newValue) { name = newValue; }
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DefaultPU");
public EntityLesson[] getLessonValue() {
EntityManager em = emf.createEntityManager();
List<EntityLesson> result;
try {
EntityTransaction entr = em.getTransaction();
boolean committed = false;
entr.begin();
try {
Query query = em.createQuery("SELECT l FROM EntityLesson l");
result = query.getResultList();
entr.commit();
committed = true;
lessonList = new EntityLesson[result.size()];
lessonList = result.toArray(lessonList);
} finally {
if (!committed) entr.rollback();
}
} finally {
em.close();
}
return lessonList;
}
public void onEditRow(RowEditEvent event) {
EntityLesson editedLesson = (EntityLesson)event.getObject();//gives me unedited value
............................
............................
}
EntityLesson.java:
#Entity
#Table(name="lessonaaa")
public class EntityLesson implements Serializable {
#Id
#Column(name="Lesson_Id", nullable=false)
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int lessonId;
#Column(name="Lessson", nullable=false, length=65)
private String lessonName;
public int getLessonId() { return lessonId; }
public void setLessonId(int lessonId) { this.lessonId = lessonId; }
public String getLessonName() { return lessonName; }
public void setLesson (String lessonName) { this.lessonName = lessonName; }
}
The problem occurs because of the JSF lifecycle:
When your dataTable is displayed it executes the JPQL to retrieve the list of lessons. After that they are displayed.
Now you edit on entity and hit save, the edited entity in the list has now the new value.
But what happens next, is that the list is fetched another time and then the listener method is executed with the newly fetched enitiy.
You can solve the problem if you store the list of entities in a local attribute in the view bean and fill it in the post construct method (annotated by #PostContruct) and you have to make the view bean #SessionScoped. Then use this list for the datatable.
My problem is similar:
The 'dataTable' contains as 'value' a list of entities:
<p:dataTable id="category" var="category" value="#{categoriesBacking.categoriesListEdit}">
If I select one for edit, the object which is passed to the event contains the previously unmodified value. I observed that this is due to the fact that dataTable's value is a list. As a work-around (to be able to use the component) I added a 'filterBy' to any of the 'column'. If the dataTable will contain only one value, that value will be interpreted correctly by the passed event in the managed bean.
!!! The event's object will be the modified instance.
I also use:
<p:ajax event="rowEdit" update="#this" listener="#{categoriesBacking.onEditRow}" />
instead of dataTable's 'rowEditListener'.
Again, this is just a workaround.
I have almost exactly the same code except instead of using the <p:ajax> tag I am instead using the rowEditListener attribute of dataTable. Try this instead:
<p:dataTable ... rowEditListener="#{lesson.onEditRow}" ... >
...
This kind of problems are generally related to your backing bean. Your "lesson" class needs #ManagedBean (javax.faces.bean.ManagedBean) annotation. Simply add
#ManagedBean (name="YourBeanName")
#ViewScoped
just before public class lesson implements Serializable { line in your lesson.java

When adding a faces message in JSF my actions aren't performed?

I have the following backing bean:
#ViewScoped
#ManagedBean
public class WeighFamilyBacking2 implements Serializable {
private static final long serialVersionUID = 1L;
private String[] children = new String[] { "Child1", "Child2", "Child3" };
private HashMap<String, Integer> newWeights;
public WeighFamilyBacking2() {
newWeights = new HashMap<String, Integer>();
for (String s : getChildren())
newWeights.put(s, new Integer(0));
}
public void distributeWeightsWithoutMessage(ActionEvent event) {
for (String s : newWeights.keySet()) {
newWeights.put(s, newWeights.get(s) + 1);
}
}
public void distributeWeights(ActionEvent event) {
for (String s : newWeights.keySet()) {
newWeights.put(s, newWeights.get(s) + 1);
}
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Succesful", "Weights redistributed."));
}
public HashMap<String, Integer> getNewWeights() {
return newWeights;
}
public List<String> getChildren() {
return Arrays.asList(children);
}
}
... And the following xhtml page:
<!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:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form>
<ui:repeat var="child" value="#{weighFamilyBacking2.children}">
<h:outputText value="#{child}" />
<h:outputText value="#{weighFamilyBacking2.newWeights[child]}" /> -
<h:outputText value="#{weighFamilyBacking2.newWeights[child]}" /> -
<h:inputText id="oz" value="#{weighFamilyBacking2.newWeights[child]}" />
<h:inputText id="lbs"
value="#{weighFamilyBacking2.newWeights[child]}" />
<br />
</ui:repeat>
<h:commandButton
actionListener="#{weighFamilyBacking2.distributeWeights}"
value="Redistribute" />
<h:commandButton
actionListener="#{weighFamilyBacking2.distributeWeightsWithoutMessage}"
value="Redistribute Without Message" />
</h:form>
</h:body>
</html>
This is a simple reproducible test case. When you click on the redistribute without message, things work as expected. When you click on the redistribute button it displays the success message but the input fields are not updated. However, the text output field is updated just one time.
I have tried using immediate=true on both buttons and that doesn't affect this. This is a very simple case, I can't understand why it doesn't work.
I have tried this with all recent versions of Mojarra including 2.1.3.
This is another <ui:repeat> anomaly. I haven't nail down the exact root cause yet so that I can check if this is already reported to the JSF guys and if necessary report it, but I can tell that it works when I replace the <ui:repeat> by a <h:dataTable>.
<h:dataTable var="child" value="#{weighFamilyBacking2.children}">
<h:column>
<h:outputText value="#{child}" />
<h:outputText value="#{weighFamilyBacking2.newWeights[child]}" /> -
<h:outputText value="#{weighFamilyBacking2.newWeights[child]}" /> -
<h:inputText id="oz" value="#{weighFamilyBacking2.newWeights[child]}" />
<h:inputText id="lbs"
value="#{weighFamilyBacking2.newWeights[child]}" />
</h:column>
</h:dataTable>
Maybe a <table> is not semantically correct for you. If this is really undesireable, you might want to check if it works without problems with Tomahawk's <t:dataList>, RichFaces' <rich:dataList>, PrimeFaces' <p:dataList>, etc each which supports rendering the children without additional markup.
Update: I reported it as issue 2157.

Resources