How to sort in primefaces columns? - sorting

So, I've been trying for 3 days now... First, i've found that primefaces has a bug with the tag p:columns, as it's sortFunction asks for a property instead a method. So, i've found this solution:
here
Nevertheless, even reaching the method, i don't know what column i'm asking to sort, as I'm not sure if its possible to pass a parameter. Anyone can help?
I'm using primefaces 5.0 here.
Here is my datatable:
<p:dataTable value="#{categoryBean.categories}" var="category">
<p:column sortBy="#{category.name}">
<f:facet name="header">
<h:outputText value="Category"></h:outputText>
</f:facet>
<h:outputText value="#{category.name}"></h:outputText>
</p:column>
<p:columns value="#{categoryBean.columns}" var="column" columnIndexVar="i" sortBy="#{category}" sortFunction="#{categoryBean.customOrder}">
<f:facet name="header">
<h:outputText value="#{column.header}">
</h:outputText>
</f:facet>
<h:outputText value="#{category[column.property][i].sumGrade/category[column.property][i].countGrade}"></h:outputText>
</p:columns>
</p:dataTable>
And here are my methods:
public MethodExpression getCustomOrder() {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getExpressionFactory()
.createMethodExpression(context.getELContext(),
"#{categoryBean.customSort}", Integer.class,
new Class[] { Object.class, Object.class });
}
public int customSort(Object val1, Object val2) {
System.out.println("mySort" + val1 + "/" + val2);
return 0;
}
So, the object can reach the method, however, i need to know how to pass a parameter or something, so i can know which column i'm refering to.
Thank you guys.

<p:dataTable> has an attribute sortBy and sortOrder
for example
<p:dataTable id="table1" var="x" value="#{myBackingBean.myEntities}" sortBy="#{x.id}" sortOrder="descending">
...assuming your backing bean object has a .getId() field.

Related

How to update outputText value based on selected checkboxes in dataTable through ajax

I need your help in updating an outputText with the total Amount field for the selected checkboxes in a dataTable. The jsf has the below code:
<p:dataTable id="PendingRequests" var="hr" selection="#{hrdirector.selectedRequests}"
value="#{hrdirector.listPendingRequests}" rowKey="#{hr.requestNo}"
filteredValue="#{hrdirector.filteredRequests}" widgetVar="dataTableWidgetVar">
<p:column selectionMode="multiple" style="width:16px;text-align:center"></p:column>
<p:column headerText="Request No.">
<h:outputText value="#{hr.requestNo}"/>
</p:column>
<p:column headerText="Request Amount">
<h:outputText value="#{hr.requestAmount}"/>
</p:column>
</p:dataTable>
<h:outputText id="Sum" value="#{hr.Sum}"/>
The user is going to select a number of checkboxes and I need to know the appropriate way to call a method through ajax to update the outputText with the Total Requests Amounts selected.
The method to be called is:
public void ShowTotal() {
try {
String [] tranAmountArr = new String[selectedRequests.size()];
for (int i = 0; i < selectedRequests.size(); i++) {
tranAmountArr[i] = selectedRequests.get(i).getEncashmentAmount();
Sum = Sum + Double.parseDouble(tranAmountArr[i]);
}
System.out.println(Sum);
} catch (Exception e) {
System.err.print(e);
e.printStackTrace();
log.error("Error in ShowTotal()");
}
}
Just add two Ajax tags inside your table:
<p:ajax event="rowSelect" listener="#{hrdirector.showTotal}"
process="#this" update="sum" />
And:
<p:ajax event="rowUnselect" listener="#{hrdirector.showTotal}"
process="#this" update="sum" />
Note: For method names, paremeters, attributtes and IDs use lowercase.
Note: I would name the method "updateTotal" instead "ShowTotal".

Update single row in JSF / Primefaces datatable using AJAX

How could I update a single row in a p:datatable when using AJAX?
I don't want to update the whole datatable because it has a lot of rows and it's going to take some time..
My layout:
<h:form id="visitForm">
<p:dataTable id="visitTable" var="visit" value="#{visitBean.findAllVisits()}">
<p:column headerText="${msgs['email']}"
<h:outputText value="#{visit.contactDetail.email}"/>
</p:column>
<p:column headerText="${msgs['clearance']}" id="clearance">
<p:commandButton value="${msgs['clearance.ok']}" actionListener="#{visitBean.makeClearanceNotOk(visit)}"/>
</p:column>
</p:dataTable>
</h:form>
I've tried out some things like update = "clearance" etc but it doesn't seem to work.
I'm using JSF 2.1 and Primefaces 5.2
You can use #row(n) search expression which does just that - it updates the nth row in a table. In order to update the current row, you need to pass row index as an argument. Set rowIndexVar="rowIdx" attribute on <p:dataTable> and then:
<p:commandButton ... update="#form:visitTable:#row(#{rowIdx})" />
Not sure if I'm late for the party but let me give my 5 cents on this subject on how to update content of a row using just plain ajax features from PrimeFaces.
1) Partial update: My first approach to update something in a specific row using PF is not exactly update the whole row, but update the regions of interest inside the row. This can be achieved by just defining the holding panels and updating them. For example:
<h:form id="testForm">
<p:dataTable id="myEntityTable" var="myEntity" value="#{myController.allEntities}">
<p:column headerText="id">
<h:outputText value="#{myEntity.id}"/>
</p:column>
<p:column headerText="last update">
<p:outputPanel id="lastUpdatePanel">
<h:outputText value="#{myEntity.lastUpdate}">
<f:convertDateTime pattern="HH:mm:ss" type="date" />
</h:outputText>
</p:outputPanel>
</p:column>
<p:column headerText="counter">
<p:outputPanel id="counterPanel">
<h:outputText value="#{myEntity.counter}"/>
</p:outputPanel>
</p:column>
<p:column headerText="increment">
<p:commandButton value="+"
actionListener="#{myController.increment(myEntity)}"
update="counterPanel, lastUpdatePanel"/>
</p:column>
</p:dataTable>
</h:form>
The trick is to update the target panels (in this example the fragment update="counterPanel, lastUpdatePanel"). This results in something like the following image:
2) Actually updating the row: Very often the previous approach works fine enough. However, if it is really needed to update the row one can follow the advice given in one of the previous answers and use the #row keyword:
<h:form id="testForm">
<p:dataTable id="myEntityTable" var="myEntity" value="#{myController.allEntities}" rowIndexVar="rowIndex">
<p:column headerText="id">
<h:outputText value="#{myEntity.id}"/>
</p:column>
<p:column headerText="last update 1">
<p:outputPanel>
<h:outputText value="#{myEntity.lastUpdate}">
<f:convertDateTime pattern="HH:mm:ss" type="date" />
</h:outputText>
</p:outputPanel>
</p:column>
<p:column headerText="last update 2">
<h:outputText value="#{myEntity.lastUpdate}">
<f:convertDateTime pattern="HH:mm:ss" type="date" />
</h:outputText>
</p:column>
<p:column headerText="counter">
<p:outputPanel>
<h:outputText value="#{myEntity.counter}"/>
</p:outputPanel>
</p:column>
<p:column headerText="increment">
<p:commandButton value="+"
actionListener="#{myController.increment(myEntity)}"
update="#form:myEntityTable:#row(#{rowIndex})"/>
</p:column>
</p:dataTable>
</h:form>
The trick is to hold each content from the columns inside a p:outputPanel and let update="#form:myEntityTable:#row(#{rowIndex})" make the job. I consciously leave the "last update 2" column without an outputPanel in order to illustrate this point:
Hence, whereas the columns "last update 1" and "counter" actually update after a click in "+" the "last update 2" column keeps unchanged. So, if you need to update a content, wrap up it with an outputPanel. It is noteworthy as well that the outputPanels holding each column content don't need an explicit id (you can add one if you want).
In the sake of completeness, in these examples I have used PF 6.2. The backbean is pretty straightforward:
package myprefferedpackage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class MyController {
private List<MyEntity> entities;
#PostConstruct
public void init() {
this.entities = new ArrayList<MyEntity>(10);
for(int i = 0; i < 10; ++i) {
this.entities.add(new MyEntity(i));
}
}
public List<MyEntity> getAllEntities() {
return entities;
}
public void increment(MyEntity myEntity) {
myEntity.increment();
}
public class MyEntity {
private int id;
private int counter;
private Date lastUpdate;
public MyEntity(int id) {
this.id = id;
this.counter = 0;
this.lastUpdate = new Date();
}
public void increment() {
this.counter++;
this.lastUpdate = new Date();
}
public int getId() {
return id;
}
public int getCounter() {
return counter;
}
public Date getLastUpdate() {
return lastUpdate;
}
}
}
Either use the 'ajax' functionality of a utility library like OmniFaces or be creative with the PrimeFaces Selectors.
In both cases you need to get access to the e.g. the 'current' row or rowId. But since that you have the buttons IN the row, that should not be a problem. I unfortunately don't have the time to create examples for you
I try with uptate = "#parent:componentAnotherColumn" and works. Only update the same row
<p:column>
<p:selectBooleanCheckbox value="#{atributoVar.booleanValue}">
<p:ajax process="#this" update="#parent:componentAnotherColumn"/>
</p:selectBooleanCheckbox>
</p:column>
<p:column>
<p:selectBooleanCheckbox id="componentAnotherColumn" value="#{!atributoVar.booleanValue}"/>
</p:column>

Primefaces "sortBy=" doesn't work

I'm developing an application using Primefaces + JSF. My data table works, but has a problem at sort sortBy=, I tried sortBy="#{pc.rota}" but it doesn't work too:
Data table show all rows, the problem I think is sortBy= or my backing bean.
page.xhtml
<h:body>
<h:form id="pcEmulation">
<p:dataTable id="dataTablePCEMulation" var="pc" value="#{pCEmulationBean.allPCEmulation}"
rows="10"
rowsPerPageTemplate="5,30,50,100,200,300"
emptyMessage="Não foi encontrado"
>
<f:facet name="header">
PC Emulation Web
</f:facet>
<p:column headerText="PC - TX OLO's" filterValue="#{pc.filtpcn}" filterMatchMode="contains" filterBy="#{pc.filtpcn}" >
<h:outputText value="#{pc.filtpcn}" />
</p:column>
<p:column headerText="Rota" sortBy="rota" >
<h:outputText value="#{pc.rota}" />
</p:column>
<p:column headerText="Origem">
<h:outputText value="#{pc.origem}" />
</p:column>
<p:column headerText="Antigo">
<h:outputText value="#{pc.epcn}" />
</p:column>
<p:column headerText="Destino">
<h:outputText value="#{pc.destino}" />
</p:column>
<p:column headerText="PC-Novo">
<h:outputText value="#{pc.realpcn}" />
</p:column>
</p:dataTable>
<p:blockUI block="dataTablePCEMulation" trigger="dataTablePCEMulation">
LOADING<br />
<p:graphicImage value="/images/loading.gif"/><br />
<p:graphicImage value="/images/tim-banner2.png" width="100px" height="45px"/>
</p:blockUI>
</h:form>
</h:body>
Backing bean:
#ManagedBean
//#ViewScoped
#SessionScoped
public class PCEmulationBean {
public List<PCEmulation> allPCEmulation;
public List<PCEmulation> getAllPCEmulation() {
PCEmulationDAO dao = new PCEmulationDAO();
try {
allPCEmulation = dao.getAll();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Problema no metodo list : " + e);
}
return allPCEmulation;
}
}
For the sort to work you need to return the same list object each time with the getter, where in your case you are returning a new list from the dao every time. So you should only fetch a new list if the list is previously null. The code inside your getter should be as below.
if (allPCEmulation == null) {
PCEmulationDAO dao = new PCEmulationDAO();
try {
allPCEmulation = dao.getAll();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Problema no metodo list : " + e);
}
}
return allPCEmulation;
As far as I know, sortBy attribute of Datatable is applied for only Primitive Data Types and String. If rota is an object, you must create method for sorting by yourself. Alternative, using sortBy="#{pc.rota.someting}" that contain Primitive Data Types or String for sorting.

Navigate to another page on rowselect of datatable in primefaces

I have a primefaces datatable where number of records are displaying.
I want navigate to another page on the rowSelect event (to edit the selected entity for example).
The closest sample/demo I could find was use the p:ajax tag to bind the rowSelect event to a listener method
http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionInstant.jsf
I also got one article for the same http://forum.primefaces.org/viewtopic.php?f=3&t=14664
, I tried to implement in same as they did.But it also didn't worked.
I am trying in this way and guide me If I missed anything.
<p:dataTable var="product" value="#{addPatientBB.patientAddList}" paginator="true" rows="10"
selection="#{addPatientBB.pat}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{addPatientBB.onRowSelect}" />
<p:column>
<f:facet name="header">
<h:outputText value="FirstName" />
</f:facet>
<h:outputText value="#{product.firstName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Email" />
</f:facet>
<h:outputText value="#{product.email}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Gender" />
</f:facet>
<h:outputText value="#{product.gender}" />
</p:column>
</p:dataTable>
And Backing bean is :
#ManagedBean
#ViewScoped
public class AddPatientBB implements Serializable
{
private Patient pat;
public Patient getPat()
{
System.out.println("tried to get pat");
return pat;
}
public void setPat(Patient pat)
{
this.pat = pat;
System.out.println("tried to set pat");
}
public void onRowSelect()
{
System.out.println("inside onRow select Method");
ConfigurableNavigationHandler configurableNavigationHandler = (ConfigurableNavigationHandler) FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
System.out.println("navigation objt created");
configurableNavigationHandler.performNavigation("Page?faces-redirect=true");
// Page is my navigation page where I wish to navigate named as
// "Page.xhtml"
System.out.println("Navigation executed");
}
}
So how can I navigate to another page on rowselect event? and how can display its values after navigationg the form.
I am able to go inside onRowSelect() method , actually problem is he is not able to get or understood that path :
configurableNavigationHandler.performNavigation("Page?faces-redirect=true");
so he is not able to print any logs after this line.
why is it so? is it because of I am using Liferay?
Pla guide me.
Well i think the onRowSelect is never executed because you defined it wrong.
Try this:
public void onRowSelect(SelectEvent event)
{
FacesContext.getCurrentInstance().getExternalContext().redirect("page.xhtml?id=" +pat.getId());
}
If u are using FacesServlet then use.jsf instead of .xhtml
public void onRowSelect(SelectEvent event)
{
FacesContext.getCurrentInstance().getExternalContext().redirect("page.jsf?id="+pat.getId());
}

DataTable Order by column erase values

I have PrimeFaces dataTable that is been filled by a Ajax call.
When I click on a column title, to order its values, the values disappear.
<p:commandButton value="Pesquisar" actionListener="#{requestController.listRequests}" update="dataTable" />
Here is my view:
<p:dataTable id="dataTable" var="order" value="#{requestController.backing.requestsList}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}">
<p:column sortBy="#{order.companyRequest}">
<f:facet name="header">
<h:outputText value="Pedido" />
</f:facet>
<h:outputText value="#{order.companyRequest}" />
</p:column>
<p:column sortBy="#{order.company.companyName}">
<f:facet name="header">
<h:outputText value="Cliente" />
</f:facet>
<h:outputText value="#{order.company.companyName}" />
</p:column>
<p:column sortBy="#{order.emissionDate}">
<f:facet name="header">
<h:outputText value="Data" />
</f:facet>
<h:outputText value="#{order.emissionDate}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:outputText>
</p:column>
<p:column sortBy="#{order.requestSituation.description}">
<f:facet name="header">
<h:outputText value="Status" />
</f:facet>
<h:outputText value="#{order.requestSituation.description}" />
</p:column>
<p:column>
<f:facet name="header">
</f:facet>
<h:form>
<h:commandLink value="Detalhes"/>
</h:form>
</p:column>
</p:dataTable>
EDIT
RequestController
#ManagedBean
#RequestScoped
public class RequestController implements Serializable
{
private RequestBacking backing;
public RequestController()
{
backing = new RequestBacking();
}
public void changeEventListener(ValueChangeEvent e)
{
backing.requestSearchType = e.getNewValue().toString();
}
public void change()
{
switch (backing.requestSearchType)
{
case "data":
backing.mask = "99/99/9999";
backing.maskSize = "10";
break;
case "cnpj":
backing.mask = " 99.999.999/9999-99";
backing.maskSize = "20";
break;
default:
backing.mask = "";
backing.maskSize = "50";
}
}
public void listRequests() throws ParseException
{
CompanyVO companyVO = new CompanyVO();
switch (backing.requestSearchType)
{
case "cnpj":
companyVO.setCnpj(backing.requestSearchValue);
break;
case "cliente":
companyVO.setCompanyName(backing.requestSearchValue);
break;
case "pedido":
backing.requestVO.setCompanyRequest(Integer.parseInt(backing.requestSearchType));
break;
}
SupplierVO supplierVO = new Support().getUserSession().getSupplier();
backing.requestVO.setEmissionDate(new Support().convertDate(backing.requestSearchValue));
backing.requestVO.setSupplier(supplierVO);
backing.requestVO.setCompany(companyVO);
backing.requestsList = new ArrayList<>(backing.getBo().getRequest(backing.requestVO));
if (backing.requestsList.isEmpty())
{
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_WARN, "Nenhum registro encontrado!", null);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
backing.requestsList = null;
}
}
..backing getter and setter
}
My requestsList is on my RequestBacking where I have all my getters and setters, please correct me if there is a better way of doing this, I'm using it because it leaves my controller cleaner.
public List<RequestVO> requestsList;
Apparently the value="#{requestController.backing.requestsList}" didn't return the same value as it did on the initial request. That can happen if it's a request scoped bean and/or if the requestsList is populated on every request based on a request based variable.
That's just a design mistake. Put the managed bean in the view scope and make sure that you aren't doing any business logic in a getter method. The nested class backing is also suspicious or it must be a poor naming.
See also:
Why JSF calls getters multiple times
How to choose the right bean scope?
Update in a nutshell, your bean should look something like this:
#ManagedBean
#ViewScoped
public class Orders {
private String query; // +getter +setter
private List<Order> results; // +getter (no setter required)
#EJB
private OrderService service;
public void search() {
results = service.search(query);
}
// Add/generate normal getters/setters (don't change them!)
}
and your view should look like this:
<h:form>
<p:inputText value="#{orders.query}" />
<p:commandButton value="Search" action="#{orders.search}" update=":tableForm" />
</h:form>
<h:form id="tableForm">
<p:dataTable value="#{orders.results}" var="order" ... rendered="#{not empty orders.results}">
...
</p:dataTable>
<h:outputText value="No results found" rendered="#{facesContext.postback and empty orders.results}" />
</h:form>

Resources