how to get the database values by using hibernate and how to display that values in a primefaces dataTable? - primefaces

Here i have some doubts.If you know the answer please post here.
How to get the list of values into database table by using hibernate?
How to display that values into primefaces dataTable?
Here i am posting what i am trying .see below
<p:dataTable id="users" value="#{user.listUsers}" var="user"
sortBy="user.id" rows="10" style="width: 30%">
<p:column>
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<h:outputText value="#{user.id}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{user.name}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Surname" />
</f:facet>
<h:outputText value="#{user.surName}" />
</p:column>
</p:dataTable>

Here i am finding the answer how to display a table values into primefaces dataTable.
Here i am placing what i am trying code.
<p:dataTable value="#{actions.messages}" var="act">
<p:column style="width:10%;text-align:left" filterBy="#{act.id}" >
<f:facet name="header">
<h:outputText value="ID" id="id" />
</f:facet>
<h:outputText value="#{act.id}" />
</p:column>
<p:column style="width:20%;text-align:left"
sortBy="#{act.action}">
<f:facet name="header">
<h:outputText value="Customer" id="customer" />
</f:facet>
<h:outputText value="#{act.action}" />
</p:column>
<p:column style="width:40%;text-align:left"
sortBy="#{act.scheduled}">
<f:facet name="header">
<h:outputText value="Date" />
</f:facet>
<h:outputText value="#{act.scheduled}" />
</p:column>
<p:column style="width:30%;text-align:left"
sortBy="#{act.status}">
<f:facet name="header">
<h:outputText value="Action" />
</f:facet>
<h:outputText value="#{act.status}" />
</p:column>
</p:dataTable>

Here is the hibernate dao class name called ActionsDao
public class ActionsDao {
public Session session;
public ArrayList<Actions> getActions() {
session = Util.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
try {
#SuppressWarnings("unchecked")
ArrayList<Actions> actionsList = (ArrayList<Actions>) session
.createQuery("from Actions").list();
tx.commit();
boolean found = false;
for (Actions actions : actionsList) {
Actions action = new Actions();
action.setId(actions.getId());
action.setAction(actions.getAction());
action.setActual(actions.getActual());
action.setAssignedBy(actions.getAssignedBy());
action.setAssignedTo(actions.getAssignedTo());
action.setScheduled(actions.getScheduled());
action.setOutcome(actions.getOutcome());
action.setStatus(actions.getStatus());
actionsList.contains(action);
found = true;
}
if (found) {
return actionsList;
} else {
return null;
}
} catch (Exception e) {
System.out.println("Error In getActions() -->" + e.getMessage());
return (null);
} finally {
session.close();
}
}
}

Here is the bean class i am developing name called Actions.
#ManagedBean(name = "actions", eager = true)
#SessionScoped
public class Actions implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String action;
private String assignedTo;
private String assignedBy;
private Date scheduled;
private Date actual;
private String outcome;
private String status;
//write here setter & getter methods of the above properties
public ArrayList<Actions> getMessages() {
ActionsDao dao = new ActionsDao();
return dao.getActions();
}
}
you can use the annotations or hbm file that yours choice to map the bean class.
Here i am using only mapping file why because, first i am trying to create annotations but it raised some problems that jar files are some problem.your using the correct jar files that not a problem you can continue the annotations otherwise hbm file is best.

Related

JSF Datatable - how to select row on button push in row

I would like a button in a Primefaces DataTable row to show a dialog showing more information about the object in the row. When I click anywhere in the row not in the button, the row is selected. However, when I press the button, the row is not selected. How may I make the row that the button is in the selected row?
This example from the Primefaces showcase sets selectedCar in the backing bean and displays a dialog containing data from the row on clicking a button in the row but leaves the row unselected:
<p:dataTable id="basicDT" var="car" value="#{dtSelectionView.cars1}">
<f:facet name="header">
Basic
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
<p:column style="width:32px;text-align: center">
<p:commandButton update=":form:carDetail" oncomplete="PF('carDialog').show()" icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{car}" target="#{dtSelectionView.selectedCar}" />
</p:commandButton>
</p:column>
</p:dataTable>
.. and this example from the same page selects a row in the table and the backing bean but an subsequent button click to display a dialog:
<p:dataTable id="singleDT" var="car" value="#{dtSelectionView.cars2}" selectionMode="single" selection="#{dtSelectionView.selectedCar}" rowKey="#{car.id}">
<f:facet name="header">
Single with Row Click
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
<f:facet name="footer">
<p:commandButton process="singleDT" update=":form:carDetail" icon="ui-icon-search" value="View" oncomplete="PF('carDialog').show()" />
</f:facet>
</p:dataTable>
I'm looking for a graceful solution where you can click any of multiple buttons in a row and select the row at the same time. Here's a use case where multiple buttons are useful - the data for the row contains two richtext fields of arbitrary size which are not easily shown in the table:
Use the var value of the primefaces dataTable attribute, to create a commandLink (or button) inside each row of the dataTable:
If the commandLink is clicked, an actionListener is invoked and sets the rows object as the selectedElement inside the dataTableDialog bean.
Once the ajax request as finished successfully, the update attribute of the commandLink forces the dialog to request the current data from the bean.
Now the JavaScript code of the oncomplete attribute shows up the dialog.
Take a look at the actionListener of the commandLink.
The rows object is stored inside member variable selectedElement. The data of this selected element is shown by the dialog.
Here you've got a nearly complete example:
<h:form id="form">
<p:dialog widgetVar="dlg" modal="true" id="dialog">
<h:outputText value="#{dataTableDialog.selectedElement.key} / #{dataTableDialog.selectedElement.val}" />
</p:dialog>
<p:dataTable
var="cur"
tableStyle="width: auto !important;"
value="#{dataTableDialog.elements}">
<p:column>
<h:outputText value="#{cur.key}" />
</p:column>
<p:column>
<h:outputText value="#{cur.val}" />
</p:column>
<p:column>
<p:commandLink
value="Read more ..."
actionListener="#{dataTableDialog.setSelectedElement(cur)}"
update="form:dialog"
oncomplete="PF('dlg').show()" />
</p:column>
</p:dataTable>
</h:form>
The bean:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
#javax.inject.Named
#javax.enterprise.context.SessionScoped
public class DataTableDialog implements Serializable {
private List<Data> elements;
private Data selectedElement;
#PostConstruct
public void init() {
elements = new ArrayList<>();
elements.add(new Data("Elem 1 Key", "Elem 1 Value"));
elements.add(new Data("Elem 2 Key", "Elem 2 Value"));
}
public List<Data> getElements() {
return elements;
}
public Data getSelectedElement() {
return selectedElement;
}
public void setSelectedElement(Data selectedElement) {
this.selectedElement = selectedElement;
}
}
The data class:
public class Data implements Serializable {
private String key, val; // +getter/+setter
public Data(String key, String value) {
this.key = key;
this.value = value;
}
}
Inspired by the primefaces show case for dataTable Selection:
if it is an option to ommit the button, this example opens a dialog on row click, including row selection.
add an ID to your DataModel
add the attributes selection, selectionMode and rowKey to the dataTable
insert <p:ajax ... /> tag inside dataTable to show the dialog on rowSelectEvent
The facelet:
<!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">
<h:head></h:head>
<h:body>
<h:form id="form">
<p:dialog
widgetVar="elementDialog" modal="true">
<p:outputPanel id="elementDetail">
<p:panelGrid
columns="2"
rendered="#{not empty bean.selectedElement}"
columnClasses="label,value">
<h:outputText value="Key: #{bean.selectedElement.key}" />
<h:outputText value="Val: #{bean.selectedElement.val}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
<p:dataTable
var="element"
value="#{bean.elements}"
selection="#{bean.selectedElement}"
selectionMode="single"
rowKey="#{element.id}"
tableStyle="width: auto !important;">
<p:ajax event="rowSelect" oncomplete="PF('elementDialog').show();" />
<p:column headerText="Key">#{element.key}"</p:column>
<p:column headerText="Val">#{element.val}"</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
<p:dataTable
var="element"
value="#{bean.elements}"
selection="#{bean.selectedElement}"
selectionMode="single"
rowKey="#{element.id}"
tableStyle="width: auto !important;">
<p:ajax
event="rowSelect"
oncomplete="PF('elementDialog').show();" />
...
</p:dataTable>
The Data class:
public class Data implements Serializable {
private int id; // + getter/setter
private String key, val; // + getter/setter
public Data(int id, String key, String value) {
super();
this.setId(id);
this.key = key;
this.value = value;
}
}
The bean:
public class Bean implements Serializable {
private List<Data> elements; // + getter
private Data selectedElement; // + getter/setter
#PostConstruct
public void init() {
elements = new ArrayList<>();
elements.add(new Data(0, "Elem 1 Key", "Elem 1 Value"));
elements.add(new Data(1, "Elem 2 Key", "Elem 2 Value"));
}
}
Hopefully this example leads you to archive your goal ... ;)

Database Update with Prepared Statement in JSF

I have mainpage.xhtml which displays entire records in my database and allows me to edit them. In case of clicling Edit button it calls mainPageController.edit() function which fills _bilgi variable in MainPageConroller class then it redirects to edit.xhtml page.
In edit.xhtml page it basically displays the values of _bilgi that are filled before in MainPageController class. There's no problem till here(probably there is but I am not aware of it.)
When I want to update one of those variables such as baslik I created a method in MainPageController which calls updateBilgi(_bilgi) in bilgiDAO class.
In UpdateBilgi it is pretty clear what it does yet it is not updating the table. It is interesting for me that when I debug and follow the variables, everything goes well but in the end it just does not update.
Another thing is when I put just a string in BilgilerDAO such is ps.setString(1, "aqa1") it works but ps.setString(2, bilgi.getBaslik()) does not eventho bilgi.getBaslik() returns the changed value.
What could be wrong?
Thank you for the answers in advance.
I hope I am clear enough.
Edit: I found the glitch. in BilgilerDAO the function updateBilgi(Bilgi bilgi)
the variable bilgi doesn't get the id from _bilgi but gets other variables. Why it wouldn't get the id?
mainpage.xhtml
<h:form id="bilgiForm">
<h:dataTable id="bilgiTable" value="#{mainPageController.bilgiListesi}"
var="bilgiler" border="1">
<h:column>
<f:facet name="header">
<h:outputText value="Başlık" />
</f:facet>
<h:outputText value="#{bilgiler.baslik}" />
<f:facet name="footer">
<h:outputText value="Başlık" />
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Bilgi Metni" />
</f:facet>
<h:outputText value="#{bilgiler.bilgi}" />
<f:facet name="footer">
<h:outputText value="Bilgi Metni" />
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Bilgi Metni" />
</f:facet>
<h:outputText value="#{bilgiler.bilgi}" />
<f:facet name="footer">
<h:outputText value="Bilgi Metni" />
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Bilgi Metni" />
</f:facet>
<h:graphicImage
value="https://canakkale.000webhostapp.com/showImage.php/?name=#{bilgiler.img.name}" />
<f:facet name="footer">
<h:outputText value="Bilgi Metni" />
</f:facet>
</h:column>
<h:column>
<fcore:facet name="header">Edit</fcore:facet>
<h:commandButton action="edit" value="Edit"
actionListener="#{mainPageController.edit()}">
<fcore:param name="id" value="#{bilgiler.id}" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
<fcore:view>
<h:form>
<fcore:view>
<h:form>
<h1>Update</h1>
<h:panelGrid border="" cellpadding="20" cellspacing="20"
columns="3">
<h:outputLabel value="Bilgi ID" />
<h:inputText value="#{mainPageController._bilgi.id}"
readonly="true" required="true" requiredMessage="Id is Required"
id="bilgiID">
</h:inputText>
<h:message for="bilgiID" />
<h:outputLabel value="Tag" />
<h:inputText value="#{mainPageController._bilgi.tag}"
readonly="true" required="true"
requiredMessage="Tag Girmeniz Gereklidir." id="bilgiTag">
</h:inputText>
<h:message for="bilgiTag" />
<h:outputLabel value="Başlık" />
<h:inputText value="#{mainPageController._bilgi.baslik}"
required="true" requiredMessage="Başlık Girmeniz Gereklidir."
id="bilgiBaslik">
</h:inputText>
<h:message for="bilgiBaslik" />
<h:outputLabel value="Bilgi Metni" />
<h:inputTextarea value="#{mainPageController._bilgi.bilgi}"
required="true" requiredMessage="Başlık Girmeniz Gereklidir."
id="bilgiBilgi">
</h:inputTextarea>
<h:message for="bilgiBilgi" />
<h:outputLabel value="Image URL" />
<h:inputText value="#{mainPageController._bilgi.img.name}"
required="true" requiredMessage="Başlık Girmeniz Gereklidir."
readonly="true" id="bilgiImgName">
</h:inputText>
<h:message for="bilgiImgName" />
<h:outputLabel value="Başlık" />
<input type="file" value="#{mainPageController._bilgi.img.image}" />
<h:commandButton action="#{mainPageController.updateRecord()}"
value="Update">
</h:commandButton>
</h:panelGrid>
</h:form>
</fcore:view>
</h:form>
</fcore:view>
</h:body>
</html>
MainPageController Class
#ManagedBean
public class MainPageController implements Serializable {
List<Bilgi> bilgiListesi = new ArrayList<Bilgi>();
private Bilgi _bilgi = new Bilgi();
private static final long serialVersionUID = 1L;
BilgilerDAO bilgiDao = new BilgilerDAO();
ImageDAO imgDao = new ImageDAO();
public MainPageController() {// Default Constructor
try {
bilgiListesi = showAllRecords();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Bilgi> showAllRecords() throws SQLException {
return bilgiDao.getAllBilgiler();
}
public List<Image> showAllImages() throws Exception {
return imgDao.getAllImages();
}
public void updateRecord() {
try {
bilgiDao.updateBilgi(_bilgi);
//imgDao.updateImage(_bilgi.getImg());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void edit() {
FacesContext fc = FacesContext.getCurrentInstance();
int id;
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
id = Integer.parseInt(request.getParameter("id"));
try {
bilgiListesi = bilgiDao.getAllBilgiler();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Bilgi bilgi : bilgiListesi) {
if (bilgi.getId() == id) {
_bilgi.setBaslik(bilgi.getBaslik());
_bilgi.setBilgi(bilgi.getBilgi());
_bilgi.setImg(bilgi.getImg());
_bilgi.setTag(bilgi.getTag());
_bilgi.setId(bilgi.getId());
}
}
}
public void edit(Bilgi bilgi) {
for (Bilgi existing : getBilgiListesi()) {
existing.setEditable(false);
}
bilgi.setEditable(true);
}
}
BilgilerDAO
#Override
public String updateBilgi(Bilgi bilgi) throws Exception {
String sql = "UPDATE bilgiler SET bilgi=?, baslik =? WHERE id=? ";
ps = DatabaseConnection.getConnection().prepareStatement(sql);
ps.setString(1, "aqa1");
ps.setString(2, bilgi.getBaslik());
ps.setInt(3, bilgi.getId());
int ex = ps.executeUpdate();
if (ex > 0) {
System.err.println("coodld");
}
ps.close();
return "mainpage";
}
I kind of solved the issue.
<h:inputText value="#{mainPageController._bilgi.id}" readonly="true" required="true" requiredMessage="Id is Required" id="bilgiID">
in this xhtml line readonly="true" caused it return null. I removed it now it works how I wanted. Though, I still want them to be displayed but not editable.

Primefaces ActionListener not fired if h:inputHidden in the datatable

I am using Primefaces 5.1 and have this strange behaviour.
If in my dataTable I have h:inputHidden then mymethod() is not fired.
The method is fired if I remove it.
<p:dataTable id="tablerisorse" value="#{myBean.resources}" var="resource"
rowStyleClass="#{(rowIndex mod 2) eq 0 ? 'oddRow' : 'evenRow'}"
rowIndexVar="rowIndex"
emptyMessage="Empty" headerClass="header">
<p:column>
<h:inputHidden id="id_user" value="#{resource.user}"/>
<f:facet name="header">
<h:outputText value="Surname"/>
</f:facet>
<h:outputText value="#{resource.surname}" />
</p:column>
<p:column>
<p:commandLink id="linkdet" actionListener="#{myBean.mymethod}" ajax="false"onstart="progressbar()" oncomplete="hideprogressbar()">
<p:graphicImage value="images/res.png" style="{border: 0}"></p:graphicImage>
</p:commandLink>
</p:column>
</p:dataTable>
the method is:
public void impegnirisorsa(ActionEvent ae) {
// TODO Auto-generated method stub
HtmlInputHidden uicid_user = (HtmlInputHidden) ae.getComponent().findComponent("id_user");
String id_user = ""+uicid_user .getValue();
System.out.println("id_user"+id_user);
}
I wonder what the problem could be and which workarounds could I use.

p:datatable summary row calculation

I have a p:dataTable pretty similar to the showcase.
Unfortunatly, the showcase uses randomly generated values for the p:summaryRow.
Refering to the showcase, imagine the car had a price attribute.
How would I sum up the price for the cars grouped by the specified column for displaying it in the summary row?
I have same problem with you and found correct usage from primefaces blog
SummaryRow from primefaces forum
this is some example show correct calculation for sum price, count...
Listener gets the group property which is the sortBy value which you can use to calculate totals or any other operation.
<p:summaryRow listener="#{backingBean.calculateTotal}">
<p:column colspan="3" style="text-align:right">
Total:
</p:column>
<p:column>
#{backingBean.total}
</p:column>
</p:summaryRow>
/* listener method in your bean */
public void calculateTotal(Object o) {
this.total = 0.0d;
String name = "";
if(o != null) {
if(o instanceof String) {
name = (String) o;
for(MyRowObject p : (List<MyRowObject>) dataTableModel.getWrappedData()) { // The loop should find the sortBy value rows in all dataTable data.
switch(sortColumnCase) { // sortColumnCase was set in the onSort event
case 0:
if(p.getcolumn0data().getName().equals(name)) {
this.total += p.getcolumn0data().getValue();
}
break;
case 1:
if(p.getcolumn1data().getName().equals(name)) {
this.total += p.getcolumn1data().getValue();
}
break;
}
}
}
}
}
this is my solution:
<p:dataTable var="elem" value="#{unitSubStatusChart.resultList}" tableStyleClass="app-table-auto">
<et:defaultPaginator />
<p:column headerText="#{bundle['class']}" sortBy="#{elem.dtype}">
<e:outputIconText icon="#{icons[elem.dtype]}" value="#{bundle[elem.dtype]}" />
</p:column>
<p:column headerText="#{bundle['status']}" sortBy="#{elem.status}">
<h:outputText value="#{bundle[elem.status]}" />
</p:column>
<p:column headerText="#{bundle['subStatus']}" sortBy="#{elem.subStatus}">
<h:outputText value="#{bundle[elem.subStatus]}" />
</p:column>
<p:column headerText="#{bundle['count']}">
<h:outputText value="#{elem.count}" />
</p:column>
<p:summaryRow listener="#{unitSubStatusChart.onSummaryRow}">
<p:column colspan="3" style="text-align:right">
<h:outputText value="#{bundle.total}:" />
</p:column>
<p:column>
<!-- !!! NOTE THIS VALUE EXPRESSION !!! -->
<h:outputText value="#{component.parent.attributes.total}" />
</p:column>
</p:summaryRow>
</p:dataTable>
and this is the listener:
public void onSummaryRow(Object filter)
{
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ELResolver elResolver = elContext.getELResolver();
DataTable table = (DataTable) UIComponent.getCurrentComponent(facesContext);
UIColumn sortColumn = table.getSortColumn();
ValueExpression expression = sortColumn.getValueExpression("sortBy");
ValueReference reference = ValueExpressionAnalyzer.getReference(expression);
String property = (String) reference.getProperty();
int total = 0;
List<?> rowList = (List<?>) table.getValue();
for(Object row : rowList)
{
Object value = elResolver.getValue(elContext, row, property);
if(filter.equals(value))
{
// THIS IS THE ONLY POINT TO CUSTOMIZE
total += ((UnitResult) row).getCount();
}
}
List<UIComponent> children = table.getSummaryRow().getChildren();
UIComponent column = children.get(children.size() - 1);
column.getAttributes().put("total", total);
}
This listener has no external references: it does not depend on previous onSort events/listeners and it doesn't need any field in the bean.
I will suggest a possible way to do this, may not be the most perfect, but i believe it will help.
Ther's the steps:
1 - Declare a class atribute to acumulate the total group value:
...
#Named(value = "myBean")
#YourScope
public class InscricaoBean implements Serializable {
...
//in this example i will use a int type
private int acumulatorAux = 0;
...
2 - Create a function to return the total value per group:
...
public int getAcumulatedValue() {
int aux = acumulatorAux ;
acumulatorAux = 0;
return aux;
}
...
3 - Create an method to acumulate values per group:
...
public void acumulateValue(int value)
{
acumulatorAux += value;
}
...
4 - On JSF page, you need to call acumulateValue method for every row, something like:
...
<p:dataTable value="#{myBean.getList()}" var="testVar">
<p:column headerText="Header" sortBy="#{testVar.name}">
#{inscricaoBean.acumulateValue(testVar.value)}
<h:outputText value="#{testVar.name}" />
</p:column>
...
5 - And next, you can have a summaryRow like:
...
<p:summaryRow>
<p:column colspan="1" style="text-align:right">
<h:outputText value="Total:" />
</p:column>
<p:column>
<h:outputText value="#{inscricaoBean.getAcumulatedValue()}" />
</p:column>
</p:summaryRow>
...
Well, this is a gross way to acomplish this task. I think you can improve, but it was the first think when i see your question.
Hope it helps.
by using Lambda expression it works in java 1.7 with EL 3.0
n your JSF it would be like this :
<p:summaryRow>
<p:column colspan="3" style="text-align:right">
<h:outputText value="Total:" />
</p:column>
<p:column>
<h:outputText value="#{car.stream().map(item->item.price).sum()}">
<f:convertNumber type="currency" currencySymbol="$" />
</h:outputText>
</p:column>
</p:summaryRow>
One approach is to pass the datatable's sortBy="#{car.brand}" value within the p:summaryRow into a backing method that uses a stream to compute price subtotal.
<h:form>
<p:dataTable var="car" value="#{dtSummaryRowView.cars}" sortBy="#{car.brand}">
<p:column headerText="Id" sortBy="#{car.id}">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year" sortBy="#{car.year}">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand" sortBy="#{car.brand}">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color" sortBy="#{car.color}">
<h:outputText value="#{car.color}" />
</p:column>
<p:summaryRow>
<p:column colspan="3" style="text-align:right">
<h:outputText value="Total:" />
</p:column>
<p:column>
<h:outputText value="#{dtSummaryRowView.brandSubtotal(car.brand)}">
<f:convertNumber type="currency" currencySymbol="$" />
</h:outputText>
</p:column>
</p:summaryRow>
</p:dataTable>
</h:form>
.
public double brandSubtotal(String brand) {
return cars.stream().filter(c -> c.getBrand().equals(brand)).mapToDouble(c -> c.getPrice()).sum();
}
Another approach is to use the listener in p:summaryRow to set a backing bean attribute and then use getter to display the attribute.
<p:summaryRow listener="#{dtSummaryRowView.computeSubtotal(car.brand)}">
<p:column colspan="3" style="text-align:right">
<h:outputText value="Total:" />
</p:column>
<p:column>
<h:outputText value="#{dtSummaryRowView.subTotal}">
<f:convertNumber type="currency" currencySymbol="$" />
</h:outputText>
</p:column>
</p:summaryRow>
.
public void computeSubtotal(String brand) {
subTotal = cars.stream().filter(c -> c.getBrand().equals(brand)).mapToDouble(c -> c.getPrice()).sum();
}
public double getSubTotal () {
return subTotal ;
}

Can't leave editing mode on prime faces roweditor

I have this code that shows a table with a prime faces datatable and a roweditor column. When I click on pencil icon, editable mode is enabled but after that, when I click on check or cancel icon nothing happens, editable mode remains active. I've search a lot about it but I couldn't find response. Listener on backing bean is not called.
This is my code of the view:
<p:dataTable var="vac" value="#{vacDocBean.obl}" id="documentacion" editable="true">
<f:facet name="header">
Table
</f:facet>
<p:ajax event="rowEdit" update="#this" listener="#{vacDocBean.onEditRow(_record)}" />
<p:column headerText="Edad">#{vacuna.inm.e}</p:column>
<p:column headerText="Inm">#{vac.inm.n}</p:column>
<p:column headerText="Fecha aplicacion">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{vac.fechaAplicacion}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:outputText>
</f:facet>
<f:facet name="input">
<p:calendar value="#{vac.fechaAplicacion}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Marca">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{vac.marca}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{vac.marca}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Lote">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{vac.lote}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{vac.lote}" style="width:100%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Editar" styleClass="ui-editable-column-options">
<!-- <p:commandLink ajax="true">-->
<p:rowEditor />
<!-- </p:commandLink > -->
</p:column>
<f:facet name="footer">
Vacunación documentada
</f:facet>
</p:dataTable>
And the backing bean:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.calendario;
#Named(value="vacDocBean")
#SessionScoped
public class VacDocBean implements Serializable {
private List<Vac> obl;
public VacDocBean() {
obl = new ArrayList<Vac>();
setVac();
Collections.sort(obl);
}
private void setVac()
{
this.obl = new ArrayList(Helper.getObl());
}
public List<Vac> getObl() {
return obl;
}
public void setObligatorias(List<Vac> obl) {
this.obl = obl;
}
public void onEditRow(RowEditEvent e){
System.out.println("Hello");
}
public void onCancel(RowEditEvent e){
System.out.println("Hello 2");
}
}
Thanks!!
Just surround your h:datatable by a h:form tag, since the editable datatable needs it.
To make your listener method work, try that, whithout changing method's signature:
<p:ajax event="rowEdit" listener="#{vacDocBean.onEditRow}" />