Columns (table body) not visible in datatable when using lazydatamodel - jsf

Using LazyDataModel does not display columns in the datatable.
I have implemented custom LazyDataModel and I have implemented load method init. However, when I pass the datamodel as a value to the datatable, the columns are not rendered/displayed. But when I pass it as a list, the columns are rendered/displayed.
My LazyDataModel class
public class SearchPmrLazyDataModel extends LazyBaseDataModel<SearchDTO> {
public SearchPmrLazyDataModel() {
}
public void setData() {
if (searchCriteria == null) {
searchCriteria = new PmrSearchCriteriaDTO();
}
setWrappedData(pmrService.searchPmr(searchCriteria, teamId));
}
#Override
public List<PmrSearchResultViewDTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
setData();
searchCriteria.setPageRequest(determinePage(first, pageSize));
List<PmrSearchResultViewDTO> data = this.cachedData;
// rowCount
int dataSize = data.size();
this.setRowCount(dataSize);
// paginate
if (dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
} catch (IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
} else {
return data;
}
}
#Override
public void setRowIndex(int rowIndex) {
if (rowIndex == -1 || getPageSize() == 0) {
super.setRowIndex(-1);
}
else
super.setRowIndex(rowIndex % getPageSize());
}
#Override
public Object getRowKey(PmrSearchResultViewDTO obj) {
return obj.getId();
}
}
My bean
public LazyDataModel<SearchDTO> getCorresLazyDataModel(String selectedTabName, String selectedStateName, String selectedStateName2) {
//returns corresponding lazy data model according to a business logic
return getLazyDataModel(selectedTabName, selectedStateName, selectedStateName2);
}
My XHTML page
<p:dataTable
value="#{formBean.getCorresLazyDataModel(pmrStatusTab, pmrState, pmrState2)}"
var="pmr" id="pmrStatusResultTable#{pmrStatusTab}#{pmrState}"
widgetVar="pmrStatusResultTable#{pmrStatusTab}#{pmrState}"
style="overflow: auto; width: auto! important; table-width:fixed"
rows="10" rowKey="#{pmr.id}" rowStyleClass="odd, even"
reflow="true" scrollWidth="#{formBean.scrollWidth}"
scrollable="true" scrollRows="10" paginator="true" lazy="true"
selectionMode="single" selection="#{formBean.selectedPmr}">
<p:ajax event="rowSelect" process="#this"
listener="#{formBean.onRowSelect}" />
<p:columns value="#{formBean.columns}" var="column"
columnIndexVar="colIndex" sortBy="#{pmr[column.property]}"
sortable="true">
<f:facet name="header">
<h:outputText value="#{column.header}" />
</f:facet>
<h:outputText value="#{pmr[column.property]}" />
</p:columns>
</p:dataTable>
The columns are not rendered/displayed only if I pass datamodel directly. If I pass the value as list, they are displayed, is there anything which I am missing?

Related

p:dataTable does not update on first attempt [duplicate]

This question already has an answer here:
How and when should I load the model from database for JSF dataTable
(1 answer)
Closed 3 years ago.
I have developed a dynamic table which should refill table at every request, the same function is being performed by the code as follows:-
html
<h:form id="form">
<p:outputLabel value="Client: " />
<p:inputText id="inp" value="#{test.id}" />
<p:inputText id="inp1" value="#{test.title}" />
<p:commandButton value="Call List" action = "#{liveRangeService.LiveRangeServicesss(10)}"/>
<p:commandButton value="Call List" action = "#{liveRangeService.LiveRangeServicesss(20)}"/>
<p:dataTable var="result" id="tbl" widgetVar="dtlTBL"
value="#{liveRangeService.tableData}"
filteredValue="#{liveRangeService.filteredData}"
paginator="false"
scrollable="true" rowIndexVar="rowindex" scrollHeight="500"
scrollRows="50" liveScroll="true"
filterDelay="1100"
>
<p:ajax event="rowSelect" listener="#{test.onRowSelect(rowindex)}" />
<f:facet name="header">
<p:outputPanel layout="inline" styleClass="tabSpacer">
<h:outputText value="Global Filter:" />
<p:inputText id="globalFilter" onkeyup="PF('dtlTBL').filter()" style="width:150px;margin-left:10px;"/>
</p:outputPanel>
</f:facet>
<p:column width="50">
<f:facet name="header">
<h:outputText value="Sr." />
</f:facet>
<p:commandButton value="#{rowindex}" style="width: 49px" action="#{test.onRowSelect(rowindex)}"/>
</p:column>
<p:columns value="#{liveRangeService.tableHeaderNames}"
var="mycolHeader"
width="#{colIndex==0?'10%':colIndex==1?'70%':colIndex==2?'10%':colIndex==3?'10%':'0'}"
columnIndexVar="colIndex"
sortBy="#{result[mycolHeader]}"
filterBy="#{result[mycolHeader]}"
filterMatchMode="contains"
>
<f:facet name="header">
<h:outputText value="#{mycolHeader}" />
</f:facet>
<h:outputText value="#{result[mycolHeader]}" />
<br />
</p:columns>
</p:dataTable>
</h:form>
#ManagedBean(name="liveRangeService", eager = true)
#Dependent
public class LiveRangeService implements Serializable {
private static List< Map<String, String> > tableData;
public static List< Map<String, String> > filteredData;
private static List<String> tableHeaderNames;
private String tableColWidths;
public List<Map<String, String>> getTableData() {
return tableData;
}
public List<String> getTableHeaderNames() {
return tableHeaderNames;
}
public LiveRangeService() {
}
public static void LiveRangeServicesss(int noOfRows) {
tableData = new ArrayList< Map<String, String> >();
filteredData = new ArrayList< Map<String, String> >();
tableHeaderNames = new ArrayList<String>();
tableHeaderNames.add("ID");
tableHeaderNames.add("Title");
tableHeaderNames.add("Opn_Amt");
tableHeaderNames.add("Smr_Amt");
for (int i = 0; i < noOfRows; i++) {
Map<String, String> playlist = new HashMap<String, String>();
playlist.put("ID", "101000" + i);
playlist.put("Title", "Share Capital - Mr. " + i);
playlist.put("Opn_Amt", "0");
playlist.put("Smr_Amt", "0");
tableData.add(playlist);
}
filteredData=tableData;
System.out.println("Filled " + filteredData.size() + ", " + noOfRows);
String dlgTBL="form:tbl";
PrimeFaces.current().ajax().update(dlgTBL);
}
public String getTableColWidths() {
return tableColWidths;
}
public void setTableColWidths(String tableColWidths) {
this.tableColWidths = tableColWidths;
}
public List<Map<String, String>> getFilteredData() {
return filteredData;
}
public void setFilteredData(List<Map<String, String>> filteredData) {
this.filteredData = filteredData;
}
}
#ManagedBean(name="test")
#SessionScoped
public class Test implements Serializable {
public String id;
public String title;
public Test() {
id="1";
title="Testing";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void onRowSelect(int row) {
try {
String i="ID";
String t="Title";
String ci="id";
String ct="title";
this.getClass().getDeclaredField(ci).set(this, LiveRangeService.filteredData.get(row).get(i));
this.getClass().getDeclaredField(ct).set(this, LiveRangeService.filteredData.get(row).get(t));
PrimeFaces.current().ajax().update("form:inp");
PrimeFaces.current().ajax().update("form:inp1");
PrimeFaces.current().executeScript("PF('dlg').hide();");
} catch (Exception e) {
System.out.println("Error! " + e.getMessage() );
}
}
}
but the problem is that when the table is needed to be updated for other query, the call of function has to be done 2 times ie. i have placed two buttons, one pressing button 1, the table is populated with 10 rows and on pressing button 2, the table is populated with 20 rows. Each button is needed to be pressed two times to update the table.
Please advice.
i have just initialized the tables in Constructor, and all worked same as required.
#ManagedBean(name="liveRangeService")
#SessionScoped
public class LiveRangeService implements Serializable {
private List< Map<String, String> > tableData;
public List< Map<String, String> > filteredData;
private List<String> tableHeaderNames;
private String tableColWidths;
public List<Map<String, String>> getTableData() {
return tableData;
}
public List<String> getTableHeaderNames() {
return tableHeaderNames;
}
public LiveRangeService() {
tableData = new ArrayList< Map<String, String> >();
filteredData = new ArrayList< Map<String, String> >();
tableHeaderNames = new ArrayList<String>();
LiveRangeServicesss (-1, false);
System.out.println("in Constructor:");
}
public LiveRangeService(int noOfRows, boolean showDialogue) {
}
public void LiveRangeServicesss(int noOfRows, boolean showDialogue) {
tableData.clear();
tableHeaderNames.clear();
filteredData.clear();
tableHeaderNames.add("ID");
tableHeaderNames.add("Title");
tableHeaderNames.add("Opn_Amt");
tableHeaderNames.add("Smr_Amt");
for (int i = 0; i < noOfRows; i++) {
Map<String, String> playlist = new HashMap<String, String>();
playlist.put("ID", "101000" + noOfRows + i);
playlist.put("Title", "Share Capital - Mr. " + noOfRows + " - " + i);
playlist.put("Opn_Amt", "0");
playlist.put("Smr_Amt", "0");
tableData.add(playlist);
}
filteredData=tableData;
System.out.println("table size: " + tableData.size() + ", " + filteredData.size());
}

PrimeFaces Datatable: How to receive selected rows values?

I use Prime Faces 6.2 to make a data table with checked column:
<p:dataTable id="#{prefix}List"
value="#{tickets}"
lazy="true"
paginator="true"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
currentPageReportTemplate="{startRecord}-{endRecord} из {totalRecords}"
rows="20"
rowKey="#{ticket.id}"
var="ticket"
emptyMessage="Записи в данной категории отсутствуют">
<p:ajax event="toggleSelect" listener="#{ticketForm.onAllSelect}" process="#this" partialSubmit="true" />
<p:ajax event="rowSelectCheckbox" listener="#{ticketForm.onSelect}" update=":protocolForm" />
<p:ajax event="rowUnselectCheckbox" listener="#{ticketForm.onUnselect}" update=":protocolForm" />
<p:ajax event="rowSelect" listener="#{ticketForm.onSelect}" update=":protocolForm" />
<p:ajax event="rowUnselect" listener="#{ticketForm.onUnselect}" update=":protocolForm" />
<p:column selectionMode="multiple" style="width:40px; text-align:center" />
More specifically, when a header checkbox is selected I want to receive all selected rows data on server-side and use IDs of each row. Also, there's logic that helps to resolve a goal of hidding/rendering a page button when at least one checkbox is selected.
For this purpose I need manualy intercept a row/checkbox selection event and record IDs from it when a button pushed, so I can't use selection attribute of dataTable using such logic.
On server-side I have several event-listeners:
private Set<AbstractMTSBUExportTicket> abstractMTSBUExportTickets = new HashSet<>();
public Set<AbstractMTSBUExportTicket> getAbstractMTSBUExportTickets() {
return abstractMTSBUExportTickets;
}
public void onSelect(SelectEvent event) {
abstractMTSBUExportTickets.add((AbstractMTSBUExportTicket) event.getObject());
}
public void onUnselect(UnselectEvent event) {
abstractMTSBUExportTickets.remove(event.getObject());
}
public void onAllSelect(ToggleSelectEvent event) {
// do smth
}
Unfortunately, ToggleSelectEvent has only information about data-table itself within.
None information about rows I couldn't find. Also I tried to add process="#this" partialSubmit="true" attributes but seems like they do different actions.
So, could you give me an example of how it's possible to retrieve such data from an event object?
Should I use another way to solve it? Thanks for your answers in advance.
You're use lazy dataTable and this doesn't stay the selection on page change.
You need set the selection param with a type of your collection
Implement getRowKey inside your LazyDataModel and remove rowKey="#{ticket.id}"
Selection with checkbox doesn't need selectionMode="multiple".
This param is only for multiple selection when click on the table row with CTRL is pressed
My sugestion is control your selected data manualy
XHTML file:
<p:dataTable id="#{prefix}List"
value="#{tickets}"
lazy="true"
paginator="true"
var="ticket"
selection="#{ticketForm.selectedTickets}"
emptyMessage="Записи в данной категории отсутствуют">
<p:ajax event="toggleSelect"
listener="#{ticketForm.onAllSelect}" partialSubmit="true"/>
<p:ajax event="rowSelectCheckbox"
listener="#{ticketForm.onSelect}" update=":protocolForm"/>
<p:ajax event="rowUnselectCheckbox"
listener="#{ticketForm.onUnselect}" update=":protocolForm"/>
<p:ajax event="rowSelect"
listener="#{ticketForm.onSelect}" update=":protocolForm"/>
<p:ajax event="rowUnselect"
listener="#{ticketForm.onUnselect}" update=":protocolForm"/>
<p:column selectionMode="multiple" style="width:40px; text-align:center" />
<!--other p:columns-->
</p:dataTable>
Managed bean:
public void onRowSelect(SelectEvent event) {
if (event != null && event.getObject() != null &&
event.getObject() instanceof Ticket) {
if (selectedTickets== null) {
selectedTickets= new ArrayList<Ticket>();
}
if (!selectedTickets.contains((Ticket) event.getObject())) {
selectedTickets.add((Ticket) event.getObject());
}
}
}
public void onRowUnselect(UnselectEvent event) {
if (event != null && event.getObject() != null &&
event.getObject() instanceof Ticket &&
selectedTickets != null && selectedTickets.contains((Ticket) event.getObject())) {
selectedTickets.remove((Ticket) event.getObject());
}
}
public void onAllRowsSelect(ToggleSelectEvent event) {
//This is the trick, you don't need receive a collection
if (event.isSelected()) {
selectedTickets = ticketService.getAllTickets();
} else {
selectedTickets = new ArrayList<Ticket>();
}
}
LazyDataModel implemention of getRowKey method:
public class LazyPragaModel extends LazyDataModel<Ticket> implements Serializable {
private TicketService ticketService;
private static final long serialVersionUID = 1L;
public LazyPragaModel(TicketService ticketService) {
this.ticketService= ticketService;
}
#Override
public Object getRowKey(Ticket ticket) {
return ticket!= null ? ticket.getId() : null;
}
#Override
public Praga getRowData(String rowKey) {
List<Ticket> tickets = (List<Ticket>) getWrappedData();
for (Ticket ticket: tickets) {
if (ticket.getId().toString().endsWith(rowKey)) {
return ticket;
}
}
return null;
}
#Override
public List<Ticket> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, Object> filters) {
setRowCount(ticketService.countLazyRecords(filters).intValue());
List<Ticket> tickets = ticketService.listLazyRecords(first, pageSize,
sortField, sortOrder.name(), filters);
return tickets;
}
}
Sugestion for your service. Generic methods for lazy dataTables:
public List<T> listLazyRecords(int first, int pageSize, String sortField,
String sortOrder, Map<String, Object> filters) {
sortOrder = sortOrder != null ? sortOrder.contains("ASC") ? "ASC" :
sortOrder.contains("DESC") ? "DESC" : null : null;
String query = " FROM " + getType().getSimpleName() + " t " +
(filters.size() > 0 ? buildLazyFilters(filters) : "") +
(sortOrder != null ? " ORDER BY " + sortField + " " + sortOrder : "");
return getManager().createQuery(query, getType())
.setFirstResult(first).setMaxResults(pageSize).getResultList();
}
public Long countLazyRecords(Map<String, Object> filters) {
String query = "SELECT COUNT(x) FROM " + getType().getSimpleName() +
" x " + (filters.size() > 0 ? buildLazyFilters(filters) : "");
return getManager().createQuery(query).getSingleResult();
}
private String buildLazyFilters(Map<String, Object> filters) {
StringBuilder filterBuild = new StringBuilder("WHERE ");
for (Map.Entry<String, Object> filter : filters.entrySet()) {
if (filter.getValue().toString().chars().allMatch(Character::isDigit)) {
filterBuild.append("( " + filter.getKey() + " = " +
filter.getValue() + " OR ");
}
filterBuild.append(filter.getKey() + " LIKE '%" +
filter.getValue().toString() + "%'");
filterBuild.append(filter.getValue().toString().chars()
.allMatch(Character::isDigit) ? ") ": "");
filterBuild.append(!filters.values().toArray()[filters.size() - 1]
.equals(filter.getValue()) ? " AND " : "");
}
return filterBuild.toString();
}
I think you are missing some things on the datatable.
Showcase: https://www.primefaces.org/showcase/ui/data/datatable/selection.xhtml
You need to add selectionMode=multiple and a selection=collection to gather the selected rows like...
<p:dataTable id="multipleDT"
var="car"
value="#{dtSelectionView.cars4}"
selectionMode="multiple"
selection="#{dtSelectionView.selectedCars}"
rowKey="#{car.id}">
Whenever you select a row or row(s) the #{dtSelectionView.selectedCars} collection will be filled with the selected rows automatically.

Rowkey is null when celledit with LazyDataModel

I am using PrimeFaces 6.1. I have implemented LazyDataModel and I am able to load the rows, owever, when I update a cell, the method onCellEdit is called but event.rowKey is always null.
<p:dataTable emptyMessage="Nessun record trovato."
style="margin-top: 50px" id="cars" var="produit"
value="#{gecomparBean.lazyModel}"
editable="true" editMode="cell" widgetVar="carsTable"
filteredValue="#{gecomparBean.filteredCars}"
rows="10"
lazy="true"
scrollRows="10"
scrollable="true" liveScroll="true" scrollHeight="250"
resizableColumns="true" resizeMode="expand"
draggableColumns="true"
rowStyleClass="#{produit.id == gecomparBean.selectedObject.id ? 'selectedRow' : null}"
>
<p:ajax event="colReorder"
listener="#{gecomparBean.onColumnReorder}" />
<p:ajax event="cellEdit" listener="#{gecomparBean.onCellEdit}"
oncomplete="updateTable()" update=":form:remote" />
Managed Bean: [Session scoped]
wrapper.setSession(activeSession.getId());
lazyModel = new LazyProductDataModel(wrapper);
LazyProductDataModel
public class LazyProductDataModel extends LazyDataModel<ProductSessionDTO> implements Serializable {
private List<ProductSessionDTO> products;
private ProductSearchWrapper wrapper;
public LazyProductDataModel(ProductSearchWrapper wrapp) throws RestRequestException {
super();
wrapper = wrapp;
}
#Override
public ProductSessionDTO getRowData(String rowKey) {
for (ProductSessionDTO car : getProducts()) {
if (car.getId() == (Long.parseLong(rowKey))) {
return car;
}
}
return null;
}
#Override
public Object getRowKey(ProductSessionDTO car) {
return car.getId();
}
#Override
public List<ProductSessionDTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
List<ProductSessionDTO> data = new ArrayList<ProductSessionDTO>();
try {
System.out.println("First " + first + " Max " + pageSize);
wrapper.setFirst(first);
wrapper.setPageSize(pageSize);
products=ServiceUtils.getInstance().getProducts(wrapper);
if (getProducts() != null) {
Comparator<ProductSessionDTO> lengthComparator = new Comparator<ProductSessionDTO>() {
#Override
public int compare(ProductSessionDTO o1, ProductSessionDTO o2) {
return Long.compare(o1.getId(), o2.getId());
}
};
Collections.sort(products, lengthComparator);
}
} catch (RestRequestException ex) {
Logger.getLogger(LazyProductDataModel.class.getName()).log(Level.SEVERE, null, ex);
}
data = products;
//rowCount
int dataSize = data.size();
this.setRowCount(1000);
//paginate
if (dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
} catch (IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
} else {
return data;
}
}
}
Note: I found a post which mentioned that we need to remove the rowkey in order for the getRowKey() to get called automatically - so I have removed that attribute.

Primefaces datatable filterBy with the displayed velue

I'm working with a datatable and dynamics columns <p:columns/> and I have a filterBy on each columns. But some columns of my table have a formatted value (example: 0 and 1 to the db and displayed as "No" and "Yes") so the filterBy used the db value. I use a converter to format my value.
edit: I use TMX key to display value in different language. This is a part of my problem.
Here my HTML
<p:dataTable
id="employeeBeanPageItems"
styleClass="table"
value="#{staffListController.model.staffSearch}"
rows="15"
sortBy="#{_item.stfFullName}"
var="_item"
draggableColumns="true"
widgetVar="itemsTable"
selectionMode="single"
rowKey="#{_item.stfId}"
resizableColumns="true"
scrollable="false"
tableStyle="width:auto"
emptyMessage="#{msg['error.no-result']}"
paginator="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,15,20,50">
<p:ajax event="rowSelect" listener="#{staffListController.onRowSelect}" />
<p:ajax event="colReorder" listener="#{staffListController.onColumnReorder}" update=":search:menuColonne"/>
<p:columns filterMatchMode="contains" headerText="#{msg[column.header]}" value="#{staffListController.columns}" var="column" columnIndexVar="colIndex" sortBy="#{_item[column.property]}" filterBy="#{_item[column.property]}">
<h:outputText value="#{_item[column.property]}" converter="StaffListConverter"/>
</p:columns>
</p:dataTable>
Here my converter
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// TODO Auto-generated method stub
Label label = new Label(value.toString());
if (value.equals("1") || value.equals("Y"))
{
label.setLabel(getRessourceBundle().getString("common.yes"));
}
else if (value.equals("0") || value.equals("N"))
{
label.setLabel(getRessourceBundle().getString("common.no"));
}
else if (value.equals("EMPLOYEE"))
{
label.setLabel(getRessourceBundle().getString("staff.employee"));
}
else if (value.equals("COMPDEV"))
{
label.setLabel(getRessourceBundle().getString("staff.cd"));
}
else if (value.equals("MAN"))
{
label.setLabel(getRessourceBundle().getString("MAN"));
}
else if (value.equals("WOMAN"))
{
label.setLabel(getRessourceBundle().getString("WOMAN"));
}
else if (value.equals("UNKNOWN"))
{
label.setLabel(getRessourceBundle().getString("UNKNOWN"));
}
return label.getLabel();
}
/**
* Label is to create an object with a String
*/
static public class Label implements Serializable {
private static final long serialVersionUID = 1L;
#Getter #Setter private String label;
/**
* Public constructor of Label
* #param String label
*
*/
public Label(String label) {
this.label = label;
}
/**
* Empty constructor
*
*/
public Label() {}
#Override
public String toString() {
return label;
}
}
}
Maybe I should used a different way to format my data but I have no idea how. The aim stay to allow the filterBy using.
add:
I tried the solution given by the first commentary with the following code in my model
public String getStfResourceLaptopFormat() {
if (stfResourceLaptop != null)
{
if (stfResourceLaptop.equals("1"))
{
return "common.yes";
}
else if(stfResourceLaptop.equals("0"))
{
return "common.no";
}
else return null;
}
else
{
return null;
}
}
The problem is that I have to return a TMK key then the filterBy use the key :/
<p:columns filterMatchMode="contains" headerText="#{msg[column.header]}" value="#{staffListController.columns}" var="column" columnIndexVar="colIndex" sortBy="#{_item[column.property]}" filterBy="#{_item[column.property]}">
<h:outputText value="#{msg[_item[column.property]]}" />
</p:columns>
Converter only convert the displayed value getAsString method does not change the object. So you have to change the value at creating the list of staffListController.model.staffSearch. When you fetching the value from DB change there itself in List

primefaces not show dataTable values with lazyModel

I'm starting with primefaces and I try use LazyModel in p:dataTable.
I already implemented the LazyModel, bean and jsf. The call's to bean and model occur's correctly and my bean return a list with elements, but my jsf show nothing.
Please, somebody know whats happen?
Bellow is my code:
JSF:
<ui:composition template="./newTemplate.xhtml">
<ui:define name="content">
content
<h:form>
<p:panel id="formFiltro">
<p:messages id="messages"/>
<h:panelGrid>
<h:outputLabel for="fieldConta" value="Número da Conta:"/>
<p:inputText id="fieldConta" value="#{log.nrConta}" label="Número da Conta">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldConta" />-->
<h:outputLabel for="fieldAgencia" value="Código da Agência:"/>
<p:inputText id="fieldAgencia" value="#{log.nrAgencia}" label="Código da Agência">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldAgencia" />-->
<center>
<p:commandButton ajax="false" value="Pesquisar" action="#{log.search}" />
</center>
</h:panelGrid>
</p:panel>
<p:dataTable var="l" value="#{log.lazyLogModel}" paginator="true" rows="5"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" id="logTable" lazy="true">
<p:column headerText="ID">
<h:outputText value="#{l.logId}" />
</p:column>
<p:column headerText="Agência">
<h:outputText value="#{l.logAgencia}" />
</p:column>
<p:column headerText="Conta">
<h:outputText value="#{l.logConta}" />
</p:column>
<p:column headerText="SO">
<h:outputText value="#{l.logSo}" />
</p:column>
<p:column headerText="Plugin">
<h:outputText value="#{l.logVersaoPlugin}" />
</p:column>
<p:column headerText="Tam F10">
<h:outputText value="#{l.logTamF10}" />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
My bean:
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
#PostConstruct
public void init()
{
this.lazyLogModel = new LazyLogModel();
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel getLazyLogModel()
{
return this.lazyLogModel;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}
My LazyModel:
public class LazyLogModel extends LazyDataModel<TbLogLog> {
private String nrConta;
private String cdAgencia;
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
/**
* #return the nrConta
*/
public String getNrConta() {
return nrConta;
}
/**
* #param nrConta the nrConta to set
*/
public void setNrConta(String nrConta) {
this.nrConta = nrConta;
}
/**
* #return the cdAgencia
*/
public String getCdAgencia() {
return cdAgencia;
}
/**
* #param cdAgencia the cdAgencia to set
*/
public void setCdAgencia(String cdAgencia) {
this.cdAgencia = cdAgencia;
}
}
Consult Method called by LazyModel:
private List<TbLogLog> getListLog(String hql, int firstResult, int sizePage) throws Exception {
List resultList = null;
try {
Session session = HubernateUtil.getSessionFactory().openSession();
if ((hql == null) || (hql.trim().length() == 0)) {
hql = QUERY_PESQUISAR_TODOS;
}
Query q = session.createQuery(hql);
if(firstResult > 0 )
q.setFirstResult(firstResult);
if(sizePage > 0)
q.setMaxResults(sizePage);
resultList = q.list();
} catch (HibernateException he) {
he.printStackTrace();
}
return resultList;
}
Everything work's fine, but my jsf don't show any result.
Thanks in advance.
Remove the init() in consultaJsf Class and update the getLazyLogModel() as follows
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel<TbLogLog> lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel<TbLogLog> getLazyLogModel()
{
if (lazyLogModel== null) {
lazyLogModel= new LazyDataModel<TbLogLog>() {
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
};
}
return listaLog;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}

Resources