Can't change page p:dataTable - jsf

I have implemented code to do a table lazy in primefaces so I have method paginated which ones retrieves info. The problem the number of each page it is not showed. So if I have 100 I only see 15 elements anymore. The page button is not showed.
Like in this screenshot:
In the bean:
#PostConstruct
public void init() {
listadoPedidos = new LazyDataModel<Pedido>() {
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public List<Pedido> load(int first, int pageSize, String sortField, sortOrder sortOrder,
Map<String, Object> filters) {
List<Pedido> lista = new ArrayList<Pedido>();
boolean ordenar = sortOrder == SortOrder.ASCENDING ? true : false;
try {
lista = commonService.obtenerListaPaginada(Pedido.class, first, pageSize, "", "", "", "", campos);
listadoPedidos.setRowCount(lista.size());
} catch (Exception e) {
e.printStackTrace();
MensajesErrores.error(e.getMessage());
}
return lista;
}
};
}
And the JSF is:
<p:dataTable
id="tablaUsuario"
rowIndexVar="secuencial"
emptyMessage="#{msgs.lbl_no_hay_datos}"
value="#{pedidoBean.listadoPedidos}"
var="_pedido"
paginator="true"
paginatorPosition="top"
style="width:100%"
selection="#{pedidoBean.pedido}"
selectionMode="single"
rowKey="#{_pedido.rowKey}"
sortBy="#{_pedido.id}"
sortOrder="DESCENDING"
lazy="true"
rows="15"
paginatorTemplate="
{CurrentPageReport}
{FirstPageLink}
{PreviousPageLink}
{PageLinks}
{NextPageLink}
{LastPageLink}
{RowsPerPageDropdown}"
rowsPerPageTemplate="15,25,50,100"
>
<p:column filterStyleClass="input-text"
styleClass="columnaDTCodigo tableCell"
headerText="#{msgs.lbl_numero}">
<h:outputText value="#{_pedido.id}" />
</p:column>
</p:dataTable>
I really donĀ“t see the error, the dropdown With number of register works well.

My mistake was in this line:
listadoPedidos.setRowCount(lista.size());
replace with
listadoPedidos.setRowCount(TOTAL_ROWS_IN_DATABASE);

Related

rowsPerPageTemplate Dropdown dissapears after selection change and clicking away

I have Datatables(PrimeFaces 8.0.1) on multiple pages, only one of them had rows and rowsPerPageTemplate attributes, now i need to modify all other DataTables in the same way. All DataTables (dataTableA,dataTableB,..) are almost identical and have own #SessionScoped Beans(ControllerA, ControllerB,..). At first all DataTables seem to be OK, but if i change the rows per page selection of a dataTableX and click away to another page/dataTable and then i turn back to dataTableX, rows per page dropdown isn't there anymore (for the rest of the session). Can anyone help please? Thank you.
listViewA.xhtml
<h:form id="listAUserForm">
<p:dataTable id="dataTableA"
value="#{controllerA.listA}"
reflow="true"
paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} #{msg.rows_per_page}: {RowsPerPageDropdown}"
currentPageReportTemplate="#{prop.current_page_report_template}"
paginatorAlwaysVisible="false"
var="entryA"
rows="#{controllerA.rowsPerPage}"
rowsPerPageTemplate="10,20,30,{ShowAll|'All'}"
rowKey="#{entryA}"
selection="#{controllerA.entriesSelected}">
<p:ajax event="rowSelectCheckbox" listener="#{controllerA.onRowSelect}" update=":toolbarA" />
<p:ajax event="rowUnselectCheckbox" listener="#{controllerA.onRowUnselect}" update=":toolbarA" />
<p:ajax event="toggleSelect" process="#this" partialSubmit="true" update=":toolbarA"/>
<p:column selectionMode="multiple" style="width:16px;text-align:center"/>
....
....
</h:form>
ControllerA.java
#ManagedBean(name = "ControllerA")
#SessionScoped
public class ControllerA extends BaseController
{
private int rowsPerPage = 10;
private List<EntryA> entries= null;
public int getRowsPerPage()
{
return rowsPerPage;
}
public void setRowsPerPage(int rowsPerPage)
{
this.rowsPerPage = rowsPerPage;
}
public List<EntryA> getListA()
{
if (entries== null)
{
entries= new ArrayList<>();
List<EntryA> tmpListA;
try
{
tmpListA= getSecurityServiceLocator().getBeanA().getAllEntries();
}
catch (SecurityException ex)
{
LOGGER.error("Error retrieving listA", ex);
return Collections.emptyList();
}
if (!isFilterExist())
{
entries.addAll(tmpListA);
return entries;
}
for (EntryA tmpEntryA : tmpListA)
{
if (tmpEntryA.filterMatch(filterValue.toLowerCase()))
{
entries.add(tmpEntryA);
}
}
}
return entries;
}
...

Primefaces datatable LazyDataModel create new row

I have a primefaces datatable which uses LazyDataModel instead Collection.
I need to implement a button which create a new row in the table (empty row in last row of actual page in datatable).
I have tried adding.
#Component("table")
#Scope("session")
public class TablaPaginada implements Serializable {
private LazyDataModel<User> users;
#PostConstruct
private void init() {
usuarios = new LazyDataModel<User>() {
private static final long serialVersionUID = 8885722005055879976L;
#Override
public List<User> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, Object> filters) {
List<User> data = getUsers(first, pageSize, sortOrder, filters);
return data;
}
};
users.setRowCount(totalRowUsers());
}
public void newRow() {
//I would do this if it was List instead LazyDataModel
//this.users.add(new User());
users.getWrappedData().add(new User()); //this does not work.
}
}
This would be the xhtml code:
<h:form>
<p:dataTable rowsPerPageTemplate="5,10,15" value="#{table.users}" var="user" paginator="true"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rows="5" lazy="true">
<p:column headerText="id" sortBy="#{user.id}" filterBy="#{user.id}">
<h:outputText value="#{user.id}" />
</p:column>
<p:column headerText="name" sortBy="#{user.name}" filterBy="#{user.name}">
<h:outputText value="#{user.name}" />
</p:column>
<p:column headerText="lastName" sortBy="#{user.lastName}" filterBy="#{user.lastName}">
<h:outputText value="#{user.lastName}" />
</p:column>
<p:column headerText="money" sortBy="#{user.money}" filterBy="#{user.money}">
<h:outputText value="#{user.money}" />
</p:column>
</p:dataTable>
<p:commandButton value="new row" action="#{table.newRow()}" update="#form"/>
</h:form>
EDIT:
my code does not create new row.
From PF documentation: <p:commandButton value="Add" actionListener="#{dtBasicView.addCar}"
oncomplete="PF('dt').addRow()" process="#this"/>
And for Lazy Datatable you may run into this issue which has a workaround: https://github.com/primefaces/primefaces/issues/3901

Primefaces slected row id == null

I have a working datatable that can list out restaurant objects.
I want to delete/edite the selected ones but when I select one the following exception shows up:
org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null!
Here is the table:
<h:form id="restaurantForm">
<p:dataTable var="restaurant"
value="#{restaurantLazyBean.lazyDataModel}" paginator="true"
rows="10" rowsPerPageTemplate="5,10,50" id="carTable" lazy="true"
selectionMode="single" selection="#{RestaurantEditBean.selected}"
rowKey="#{restaurant.id}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}">
<p:ajax event="rowSelect"
listener="#{RestaurantEditBean.onRowSelect()}"/>
<p:column headerText="ID">
<h:outputText value="#{restaurant.id}" />
</p:column>
</p:dataTable>
</h:form>
Now all ids appear in the table but on selection the exception shows up.
I tried to do everything according to the primefaces example. But they didn't even have the rowKey attribute.
Heres the bean if thats relevant.
#Named("RestaurantEditBean")
#ViewScoped
#EJB(name = "ejb.RestaurantService", beanInterface = RestaurantService.class)
public class RestaurantEditBean {
#EJB
private RestaurantService restaurantService;
private RestaurantDTO selected;
public void onRowSelect(SelectEvent event) {
selected = ((RestaurantDTO) event.getObject());
}
public RestaurantService getRestaurantService() {
return restaurantService;
}
public void setRestaurantService(RestaurantService restaurantService) {
this.restaurantService = restaurantService;
}
public RestaurantDTO getSelected() {
return selected;
}
public void setSelected(RestaurantDTO selected) {
this.selected = selected;
}
}
Primefaces: 5.3
JSF: 2.2
I found out that I did a terrible mistake.
In my LazyDataModel I had to override a function.
#Override
public RestaurantDTO getRowData(String rowKey) {
Long id = Long.parseLong(rowKey);
return restaurantService.findById(id);
}
The issue was cause by the previous Long.getLong(rowKey) and that one returned null.

Getting a NullPointerException through p:ajax listener

I have app.xhtml and there is a data table and panels. I'm using Apache Tomcat server. I deployed the project and there was no problem with this datatable select listener. But the project has been deployed for a week and I got a NullPointerException in datatable row select listener afterwards. When I restarted the Tomcat, the problem was solved itself. This problem occurs on every 7, 8 days period and restarting Tomcat solves this problem.
Data table is lazy and there is Person and Applications classes. Every person has many applications.
Below, some part of app.xhtml
<p:dataTable id="appDataTable"
var="applications"
value="#{appView.applicationLazy}"
rowKey="#{applications.id}"
paginator="true" rows="20"
emptyMessage="#{"No Record"}"
currentPageReportTemplate=" #{"Page"} ({currentPage}/{totalPages})"
paginatorTemplate="{CurrentPageReport}
{FirstPageLink} {PreviousPageLink}
{PageLinks} {NextPageLink} {LastPageLink}
{RowsPerPageDropdown}"
rowsPerPageTemplate="20,50,100"
lazy="true"
selection="#{appView.selectedApplication}" selectionMode="single">
<p:ajax event="rowSelect"
onstart="ustPanel.collapse();"
update="detailPanel"
listener="#{appView.datatableRowSelectListener()}"/>
<p:ajax event="rowUnselect" update="detailPanel"/>
<f:facet name="header">
#{"Applications"}
</f:facet>
<p:column headerText="#{"name"}"
sortBy="#{appView.person.name}"
filterBy="#{appView.person.name}" >
<h:outputText value="#{appView.person.name}" >
</h:outputText>
</p:column>
<p:column headerText="#{"surname"}"
sortBy="#{appView.person.surname}"
filterBy="#{appView.person.surname}" >
<h:outputText value="#{appView.person.surname}" />
</p:column>
<p:column headerText="#{"mobilePhone"}"
sortBy="#{appView.person.mobilePhone}"
filterBy="#{appView.person.mobilePhone}"
>
<h:outputText value="#{appView.person.mobilePhone}" />
</p:column>
<p:column headerText="#{"date"}"
sortBy="#{appView.date}"
filterBy="#{appView.date}" >
<h:outputText value="#{appView.showDate(applications.date)}" />
</p:column>
<f:facet name="footer">
#{"total records"}: #{appView.applicationLazy.rowCount}
</f:facet>
</p:dataTable>
Also here some part of AppView bean class;
#ManagedBean
#ViewScoped
public class AppView extends BaseView implements Serializable {
private Applications selectedApplication;
private String name;
private String surname;
private String mobile;
private String date;
#PostConstruct
public void init() {
applicationLazy = new LazyDataModel<Basvurular>() {
#Override
public List<Applications> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
applicationLazy.setRowCount(commonService.applicationsProjection(filters));
return commonService.applicationsLazyLoad(first, pageSize, sortField, sortOrder, filters);
}
};
}
public void datatableRowSelectListener() {
try {
Locale loc = new Locale("tr", "TR");
date = selectedApplication.getDate();
name = selectedApplication.getPerson().getName().toUpperCase(loc);
surname = selectedApplication.getPerson().getSurname().toUpperCase(loc);
mobile = selectedApplication.getPerson().getMobilePhone();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Here the exception on Tomcat:
java.lang.NullPointerException
javax.el.ELException: /app.xhtml #55,173 listener="#{appView.datatableRowSelectListener()}": java.lang.NullPointerException
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
at
org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:53)
at
org.primefaces.event.SelectEvent.processListener(SelectEvent.java:40)
at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:102)
at
javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769)
at javax.faces.component.UIData.broadcast(UIData.java:893)
at
javax.faces.component.UIData.broadcast(UIData.java:915)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
at
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute
(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute
(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:508)
at

"p: datatable" selection

I am using a p:datatable and selection to handle in my bean the selected record. This works. But I want to preset a selected row when initializing the datatable. Is this possible? How?
Now it doesn't preset a record, even though selectedCompany is set. Is it because I do it before the return to jsf has been made?
This is the code I have
Bean
public Map<String, Object> getSelectedCompany() {
return selectedCompany;
}
public void setSelectedCompany(Map<String, Object> selectedCompany) {
this.selectedCompany = selectedCompany;
}
public MWSGenericMapList getHandlingCompanies() {
if (companyItems == null) {
companyItems = retrieveHandlingCompanyItems(partnerIds);
for (int i = 0; i < companyItems.size(); i++) {
if (companyItems.get(i).get("businesspartnerid").equals(getnewCustomerPartnerId())) {
setSelectedCompany(companyItems.get(i));
}
}
}
return companyItems;
}
Jsf
<p:dataTable styleClass="ptable100" id="handlingCompanies" var="company" value="#{switchCompany.handlingCompanies}" width="100%" height="200"
emptyMessage="#{msg.all_lists_no_records_found}" paginator="true" rows="10" rowsPerPageTemplate="5,10,20,50,100"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} #{msg.all_lists_numberOfRowsDisplayed_label} {RowsPerPageDropdown}"
selection="#{switchCompany.selectedCompany}" selectionMode="single" rowKey="#{company.businesspartnerid}">
<p:ajax event="rowSelect" update="#form" listener="#{switchCompany.handleCompanyChange}"/>
nevermind, the selected row did get set, I was just not on the first page (too many rows to display on 1 page) so I missed it. But it works the way I did it.

Resources