I have a datatable with search field and commandLink to sort. The commandLink that I use to trigger sorting is located not in column header but on the header of datatable. When I load my page and use only commandLink to sort everything works ok. Table sorts in two orders and I see result on my page. Problem appears when I search something in globalFilter. It also works, but after that I cant sort my table. I clear inputText of globalFilter and I cant sort table. To sum up, I see result of sorting only when I not use search field. Sort operation works but request not update the datatable. I put my code below. Maybe somebody knows how to solve it.
<ui:composition>
<p:panel header="Moje pomiary" footer="#{msgs.footer}" id="myMeasurement">
<h:form id="form" prependId="false">
<p:dataTable var="m" value="#{myMeasurementTable.measurement}" id="measureList" editable="true"
widgetVar="mTable"
emptyMessage="No files found with given criteria" filteredValue="#{myMeasurementTable.filteredMeasurement}" >
<f:facet name="header">
Sortowanie według: <p:commandLink id="sortByName" actionListener="#{myMeasurementTable.sortByName}" update="measureList">
<h:outputText value="nazwa pliku" />
</p:commandLink>
|<h:commandLink action="#{myMeasurementTable.sortByArchivisationDate}"> data archiwizacji </h:commandLink>
|<h:commandLink action="#{myMeasurementTable.sortByMeasureDate}"> data badania </h:commandLink>
<p:outputPanel styleClass="searchPanel">
<h:outputText value="Szukaj: " />
<p:inputText styleClass="globalFilter" id="globalFilter" onkeyup="mTable.filter()" style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column headerText="Informacje pomiarowe" style="width:125px" filterStyle="display:none" filterBy="#{m.fileName} #{m.measureDate} #{m.place} #{m.archivisationDate}"
filterMatchMode="contains" >
<p:separator styleClass="separatorColumn"/>
Nazwa pliku: <h:outputText value="#{m.fileName}" /><br />
Data badania: <h:outputText value="#{m.measureDate}" /><br />
Data archiwzacji: <h:outputText value="#{m.archivisationDate}" /><br />
Miejscowość: <h:outputText value="#{m.place}"/> <br />
Współrzędne GPS:
</p:column>
<p:column headerText="Wykresy">
<img src="/tmp/21/myfile.xls/myfile.xls_Parametr x.png" width="150"/>
</p:column> </p:dataTable></h:form></p:panel></ui:composition>
and part of my bean
#ManagedBean(name = "myMeasurementTable")
#ViewScoped
public class myMeasurementTable implements Serializable{
private static final long serialVersionUID = -9193902657201234669L;
private List<Measurement> measurement;
private List<Measurement> filteredMeasurement;
private boolean sortAscending = true;
public myMeasurementTable() {
measurement = new ArrayList<Measurement>();
fillTable(measurement);
}
public String sortByName() {
System.out.println("naciskam sortowanie");
if (sortAscending) {
Collections.sort(measurement, new Comparator<Measurement>() {
#Override
public int compare(Measurement m1, Measurement m2) {
return m1.getFileName().compareTo(m2.getFileName());
}
});
sortAscending = false;
} else {
Collections.sort(measurement, new Comparator<Measurement>() {
#Override
public int compare(Measurement m1, Measurement m2) {
System.out.println(m2.getFileName());
return m2.getFileName().compareTo(m1.getFileName());
}
});
sortAscending = true;
}
return null;
}
Ok I found solution on primefaces forum. It's simple. I only added oncomplete="mTable.filter()" to commandButton and everything works as I want.
Related
I'm working on a theme for an app I'm making with PrimeFaces 6.2 (community edition) and I'd like to get my simulated DAO objects working before I proceed with my css templating.
I've got an issue I came across in the past and I can't find the right answer for it again. Would someone point out an error I've made somewhere in my code?
Details:
I've made a somewhat complex DataTable using PrimeFaces LazyDataModel with little help from PrimeFaces Showcase pages. My main issue is, when I write something in the filter fields or click on any column headers to do data sorting or even click on pagination buttons I get an unexpexted data rendering issue.
Filtered, sorted and paginated results get displayed in a single concatenated row what I don't want. I've posted images and code further below for insight.
Also, I'd like to point out:
No exceptions in JS console.
No exceptions in Java console.
don't mind the missing pagination icons (text-indent: 0;)
XHTML:
<h:form id="input-form-dt2">
<H4>DATA TABLE - LAZY MODEL</H4>
<div class="flex-container">
<p:outputPanel id="dev-input-panel-13">
<p:dataTable var="DOTable" value="#{dtModelLazy.DOTList}" paginator="true" rows="10" rowKey="#{DOTable.userID}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15,25,50" selectionMode="single" selection="#{dtModelLazy.selectedObj}" id="DTModelB" lazy="true">
<p:ajax event="rowSelect" listener="#{dtModelLazy.onRowSelect}" update="input-form-dt2:dlgDTOObjDetail" oncomplete="PF('DTObjDialog').show()" />
<p:column headerText="User ID" sortBy="#{DOTable.userID}" filterBy="#{DOTable.userID}" filterMatchMode="contains">
<h:outputText value="#{DOTable.userID}" />
</p:column>
<p:column headerText="Name" sortBy="#{DOTable.name}" filterBy="#{DOTable.name}" filterMatchMode="contains">
<h:outputText value="#{DOTable.name}" />
</p:column>
<p:column headerText="Surname" sortBy="#{DOTable.surname}" filterBy="#{DOTable.surname}" filterMatchMode="contains">
<h:outputText value="#{DOTable.surname}" />
</p:column>
<p:column headerText="Age" sortBy="#{DOTable.age}" filterBy="#{DOTable.age}" filterMatchMode="contains">
<h:outputText value="#{DOTable.age}" />
</p:column>
<p:column headerText="Address" sortBy="#{DOTable.address}" filterBy="#{DOTable.address}" filterMatchMode="contains">
<h:outputText value="#{DOTable.address}" />
</p:column>
<p:column headerText="City" sortBy="#{DOTable.city}" filterBy="#{DOTable.city}" filterMatchMode="contains">
<h:outputText value="#{DOTable.city}" />
</p:column>
<p:column headerText="Post code" sortBy="#{DOTable.postCode}" filterBy="#{DOTable.postCode}" filterMatchMode="contains">
<h:outputText value="#{DOTable.postCode}" />
</p:column>
<p:column headerText="Country code" sortBy="#{DOTable.countryCode}" filterBy="#{DOTable.countryCode}" filterMatchMode="contains">
<h:outputText value="#{DOTable.countryCode}" />
</p:column>
<p:column headerText="Phone number" sortBy="#{DOTable.phoneNumber}" filterBy="#{DOTable.phoneNumber}" filterMatchMode="contains">
<h:outputText value="#{DOTable.phoneNumber}" />
</p:column>
<p:column headerText="Avatar hash" sortBy="#{DOTable.photoID}" filterBy="#{DOTable.photoID}" filterMatchMode="contains">
<h:outputText value="#{DOTable.photoID}" />
</p:column>
</p:dataTable>
<p:dialog id="dlgDTOObjDetail" header="DataTable Object Detail" widgetVar="DTObjDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="DTObjDetail">
<p:panelGrid columns="2" rendered="#{not empty dtModelLazy.selectedObj}" columnClasses="label,value">
<h:outputText value="User ID: " />
<h:outputText value="#{dtModelLazy.selectedObj.userID}" />
<h:outputText value="Name: " />
<h:outputText value="#{dtModelLazy.selectedObj.name}" />
<h:outputText value="Surname: " />
<h:outputText value="#{dtModelLazy.selectedObj.surname}" />
<h:outputText value="Age: " />
<h:outputText value="#{dtModelLazy.selectedObj.age}" />
<h:outputText value="Address: " />
<h:outputText value="#{dtModelLazy.selectedObj.address}" />
<h:outputText value="City: " />
<h:outputText value="#{dtModelLazy.selectedObj.city}" />
<h:outputText value="Post code: " />
<h:outputText value="#{dtModelLazy.selectedObj.postCode}" />
<h:outputText value="Country code: " />
<h:outputText value="#{dtModelLazy.selectedObj.countryCode}" />
<h:outputText value="Phone number: " />
<h:outputText value="#{dtModelLazy.selectedObj.phoneNumber}" />
<h:outputText value="Photo hash: " />
<h:outputText value="#{dtModelLazy.selectedObj.photoID}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</p:outputPanel>
</div>
<hr></hr>
</h:form>
LAZY MODEL:
public class DataTableModelLazy extends LazyDataModel<DODataTable> {
private static final long serialVersionUID = -2647349397077805782L;
private List<DODataTable> datasource;
public DataTableModelLazy(List<DODataTable> datasource) {
this.datasource = datasource;
}
#Override
public DODataTable getRowData(String rowKey) {
for(DODataTable dtObj : datasource) {
if(dtObj.getUserID().equals(rowKey))
return dtObj;
}
return null;
}
#Override
public Object getRowKey(DODataTable dtObj) {
return dtObj.getUserID();
}
#Override
public List<DODataTable> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
List<DODataTable> data = new ArrayList<DODataTable>();
//filter
for(DODataTable dtObj : datasource) {
boolean match = true;
if(filters != null) {
for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
Object filterValue = filters.get(filterProperty);
Field field = dtObj.getClass().getDeclaredField(filterProperty);
field.setAccessible(true);
String fieldValue = String.valueOf(field.get(dtObj));
field.setAccessible(false);
if(filterValue == null || fieldValue.startsWith(filterValue.toString())) {
match = true;
} else {
match = false;
break;
}
} catch(Exception e) {
match = false;
}
}
}
if(match) {
data.add(dtObj);
}
}
//sort
if(sortField != null) {
Collections.sort(data, new DataTableModelLazySorter(sortField, sortOrder));
}
//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;
}
}
}
VIEW BEAN:
#Named("dtModelLazy")
#ViewScoped
public class DataGeneratorBeanLazy implements Serializable {
private static final long serialVersionUID = -5918527333909822277L;
private LazyDataModel<DODataTable> DOTList;
private DODataTable selectedObj;
#Inject
private DataGeneratorBean dataGen;
#PostConstruct
public void init() {
DOTList = new DataTableModelLazy(dataGen.createDTObjects(1500));
}
public LazyDataModel<DODataTable> getDOTList() {
return DOTList;
}
public void setDOTList(LazyDataModel<DODataTable> dOTList) {
DOTList = dOTList;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("DataTable object selected!", ((DODataTable) event.getObject()).getUserID());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public DODataTable getSelectedObj() {
return selectedObj;
}
public void setSelectedObj(DODataTable selectedObj) {
this.selectedObj = selectedObj;
}
}
Update 1
I have modified the update property as update="input-form-dt2:dlgDTOObjDetail"to meet the suggestion provided. Also, I added the id property for the dialog. The issue still remains.
Update 2
I've changed my approach and started with the basic DataTable first. Also, I've stripped the .xhtml to a bare minimum. It contains only a form with the DataTable inside like so:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<div>
UI components design
</div>
<h:form id="input-form-dt1">
<h4>DATA TABLE - BASIC</h4>
<p:dataTable id="DTableA" var="dataObject" value="#{dataTableBean.objectList}" paginator="true" rows="10" rowKey="#{dataObject.id}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15,25,50">
<p:column headerText="User ID" sortBy="#{dataObject.userID}" filterBy="#{dataObject.userID}" filterMatchMode="contains">
<h:outputText value="#{dataObject.userID}" />
</p:column>
<p:column headerText="Name" sortBy="#{dataObject.name}" filterBy="#{dataObject.name}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.name}" />
</p:column>
<p:column headerText="Surname" sortBy="#{dataObject.surname}" filterBy="#{dataObject.surname}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.surname}" />
</p:column>
<p:column headerText="Age" sortBy="#{dataObject.age}" filterBy="#{dataObject.age}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.age}" />
</p:column>
<p:column headerText="Address" sortBy="#{dataObject.address}" filterBy="#{dataObject.address}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.address}" />
</p:column>
<p:column headerText="City" sortBy="#{dataObject.city}" filterBy="#{dataObject.city}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.city}" />
</p:column>
<p:column headerText="Post code" sortBy="#{dataObject.postCode}" filterBy="#{dataObject.postCode}" filterMatchMode="contains" >
<h:outputText value="#{DOTable.postCode}" />
</p:column>
<p:column headerText="Country code" sortBy="#{dataObject.countryCode}" filterBy="#{dataObject.countryCode}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.countryCode}" />
</p:column>
<p:column headerText="Phone number" sortBy="#{dataObject.phoneNumber}" filterBy="#{dataObject.phoneNumber}" filterMatchMode="contains" >
<h:outputText value="#{dataObject.phoneNumber}" />
</p:column>
<p:column headerText="Avatar hash" sortBy="#{dataObject.photoID}" filterBy="#{dataObject.photoID}" filterMatchMode="contains">
<h:outputText value="#{dataObject.photoID}" />
</p:column>
</p:dataTable>
</h:form>
</ui:composition>
As you can see I've also removed all event listeners. I've added a new field to my data object (id of type Integer) and bound DataTables rowKey to it (previously bound to userID of type String - not a good idea). My DataTable backing bean is now as basic as it can be:
#Named("dataTableBean")
#ViewScoped
public class DataTableBean implements Serializable {
private static final long serialVersionUID = -1662465661106141910L;
private List<DTObject> objectList;
#Inject
private DataGeneratorBean dataGen;
#PostConstruct
public void init() {
setObjectList(dataGen.createDTObjects(1500));
}
public List<DTObject> getObjectList() {
if (objectList == null) {
return new ArrayList<>();
} else {
return objectList;
}
}
public void setObjectList(List<DTObject> objectList) {
this.objectList = objectList;
}
}
Now, there are no custom filters, sorters or paginators of any type, not even a data model, just raw data objects in a simple list. The output result is exactly the same as before when paginator buttons are clicked or data gets filtered. All resulting data still gets displayed in a single concatenated line.
ANSWER:
As Kukeltje pointed out in the comments I've made a complete nonsense in my main container and added an autoupdate component to it. That component messed up my data table events, loading data without a table to hold it. Once I've removed the component from my main container, everything worked out. Here is the code for my main container (commented out the troublemaker).
<div id="content-window">
<p:outputPanel id="content-panel">
<ui:include src="#{contentLoaderBean.mainContent}" />
<!-- <p:autoUpdate /> -->
</p:outputPanel>
</div>
The only situations I've seen this happening is when the datatable is fully updated in addtion to a partial update of the datatable via an event (page or filter or sort or...) In the rowSelect you do seem to update the full form which contains the datatable as well. That is bad practice and can as mentioned result in what you seem so remove that.
But...in your question there are no filter ajax events that explicitly update the full datatable so that cannot cause it. Yet with 99% vertainty there is something fully updates the datatable. Three options
there is something in your live code you left out of the datatable in your question
There is something else outside the code you posted that plays havoc (an autoupdate e.g),
an update from the server side is being done in a method
Sidenote: It works with Command-Buttons.
What I Have:
A simple form where name and address from a customer are entered. In a data-table below, each row contained (in the working version) the following fields:
Name of the customer
A Command-Button which redirects to another page and shows the customers orders (This worked using <p: commandButton immediate="true">)
Another Command-Button which displayed the past orders.
Another Command-Button which was responsible for updating customer-data.
Since I didn't want to have three Command-Buttons in each row I decided to use a Split-Button.
Problem:
<p:splitButton immediate="true">
The form asks me to fill the missing data (name and address) which are set to required="true.
Question:
As far as I understand the attribute immediate="true is used to overcome this issue. So what am I missing ?
Code:
<h:form>
<p:growl id="growl" sticky="false" life="3500" showDetail="false"/>
<h:panelGrid id="customer_grid" columns="2" cellspacing="1" cellpadding="5">
<h:outputLabel id="label" for="name" value="Kunde:" style="font-weight:bold"/>
<p:inputText id="name" value="#{customerController.customer.name}" required="true" requiredMessage="Name eingeben!"/>
<h:outputLabel for="address" value="Adresse:" style="font-weight: bold" />
<p:inputText id="address" value ="#{customerController.customer.address}" required="true" requiredMessage="Adresse eingeben!"/>
<p:commandButton action = "#{customerController.createCustomer}" value="Speichern" style="margin-right:10px"
actionListener="#{growlController.saveMessage}" ajax="true"
onclick="PF('blockUIWidget').block()" oncomplete="PF('blockUIWidget').unblock()" styleClass="save-button"/>
<p:commandButton onclick="history.back(); return false;" value="Abbrechen" ajax="true"/>
<pe:blockUI widgetVar="blockUIWidget">
<h:panelGrid columns="2">
<p:graphicImage id="loader" name="images/ajax-loader.gif" style="margin-right: 12px; vertical-align: middle;" rendered="true"/>
<h:outputText value="Please wait..." style="white-space: nowrap;"/>
</h:panelGrid>
</pe:blockUI>
</h:panelGrid>
<br/>
<br/>
<p:dataTable var="customer" value="#{customerController.allCustomers}" resizableColumns="true" tableStyle="width: auto"
rendered="#{not empty customerController.allCustomers}">
<p:column headerText="customer" style="width: 300px">
<h:outputText value="#{customer.name}" />
</p:column>
<p:column>
<p:splitButton value="current order" action="#{userController.setup(customer, 'lastOrder')}" immediate="true">
<p:menuitem value="old orders" action="#{userController.setup(customer, 'oldOrders')}" immediate="true"/>
<p:menuitem value="edit" action="#{userController.setup(customer, 'update')}" immediate="true"/>
</p:splitButton>
</p:column>
</p:dataTable>
EDIT:
According to the comment of BalusC I've put the two parts in separate forms.
Effect: The message to fill out the above form does not show up, but the redirect is not happening either.
EDIT2:
The purpose of the method userController.setup(customer, 'String') is basically to inject the customer who is represented for each row. The String is returned for redirecting purposes which are set in the faces-config.xml and as I said: It works when I use Command-Buttons instead.
CODE:
#Named
#SessionScoped
public class UserController implements Serializable{
#Inject
private Customer customer;
#EJB
private CustomerService customerService;
public UserController(){
}
public List<Item> getItems(){
return customerService.getItems(customer);
}
public Ordery getCurrentOrder(){
return customerService.getCurrentOrder(customer);
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public String setup(Customer customer, String nav){
this.customer = customer;
return nav;
}
public void update(){
customerService.update(customer);
}
}
I have a problem debugged for all half day. I still could not figure it out. Basically, I use datatable expandable feature to show some extra options for each row. User could check some or none of them, then user click on update button to update database. So one row will have many options.
<f:selectItems value="#{adminBean.allTabNames}" /> is to use collect users' selected options, then managed bean will save them into database once user clicks update.
Then problem is that public void setSelectedTabsNames(List<String> selectedTabsNames) {
this.selectedTabsNames = selectedTabsNames;
} method is called several times with expected values or null values(empty list). The values are passed randomly, sometimes there are no values.
View:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:form id="form1">
<p:growl id="growl" showDetail="true"/>
<p:dataTable var="user" value="#{adminBean.users}" scrollable="false"
>
<p:ajax event="rowToggle" listener="#{adminBean.onRowToggle(user.id)}" update=":form:tabView:form1:growl" />
<f:facet name="header">
All Users
</f:facet>
<p:column style="width:2%">
<p:rowToggler />
</p:column>
<p:column headerText="First Name">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column headerText="Last Name">
<h:outputText value="#{user.lastname}" />
</p:column>
<p:column headerText="Password">
<h:outputText value="#{user.password}" />
</p:column>
<p:column headerText="Active">
<h:outputText value="#{user.active}" />
</p:column>
<p:column headerText="Last Login">
<h:outputText value="#{user.timestamp}" />
</p:column>
<p:column headerText="Notes">
<h:outputText value="#{user.notes}" />
</p:column>
<p:rowExpansion>
<h:panelGrid id="display" columns="1" cellpadding="4">
<h:outputText value="Tabs: " />
<p:selectManyCheckbox id="grid" value="#{adminBean.selectedTabsNames}"
layout="pageDirection" >
**<f:selectItems value="#{adminBean.allTabNames}" />**
</p:selectManyCheckbox>
</h:panelGrid>
<br/>
<p:commandButton value="Update" id="submit" actionListener="#{adminBean.updateTabsForUser(user.id)}" ajax="true" />
</p:rowExpansion>
</p:dataTable>
</h:form>
Managed Bean:
setSelectedTabsNames(List selectedTabsNames)
package org.userlogin.view;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import org.userlogin.db.entity.FopsUser;
import org.userlogin.service.UserService;
#ManagedBean
#ViewScoped
public class AdminBean implements Serializable {
private static final long serialVersionUID = -9002632063713324598L;
private List<FopsUser> users;
private List<String> selectedTabsNames;
private List<String> allTabNames;
private UserService us;
public AdminBean() {
us = new UserService();
users = us.getAllUsers();
allTabNames = us.getAllTabs();
}
public List<FopsUser> getUsers() {
return users;
}
public void setUsers(List<FopsUser> users) {
this.users = users;
}
public void setSelectedTabsNames(List<String> selectedTabsNames) {
this.selectedTabsNames = selectedTabsNames;
}
public List<String> getSelectedTabsNames() {
return selectedTabsNames;
}
public List<String> getAllTabNames() {
return allTabNames;
}
public void setAllTabNames(List<String> allTabNames) {
this.allTabNames = allTabNames;
}
public void updateTabsForUser(Long uid) {
us.updateTabsUser(selectedTabsNames);
}
public void onRowToggle(Long uid) {
//set current selected user
us.setCurrent(uid);
this.selectedTabsNames = us.getTabNamesByUserId(uid);
}
}
---------------update-------
Remove the nested 'form', but still not working. I found the the issue is not affecting the last row of data table. Suppose I have three rows in data table, the setters are called multiple times and set to null at last time when I manipulate the first two rows. But for the last row, the setter is still called multiple times. The last call sets the expected value. Now I just add
public void setSelectedOptions(List<String> selectedOptions) {
if (selectedOptions == null || selectedOptions.size() == 0) {
return;
}
this.selectedOptions = selectedOptions;
}
It is still ugly ...
------------update----------
<p:selectManyCheckbox id="grid" value="#{user.selectedTabsNames}"
layout="pageDirection" >
**<f:selectItems value="#{adminBean.allTabNames}" />**
</p:selectManyCheckbox>
Should design like this: put selectedTabsNames into User object. But still not working. since I have this ajax submit button, this requests each selectedTabsNames got called with empty list passed in.
<p:rowExpansion>
<h:panelGrid id="display" columns="1" cellpadding="4">
<h:outputText value="Tabs: " />
<p:selectManyCheckbox id="grid" value="# {user.selectedTabsNames}"
layout="pageDirection" >
<f:selectItems value="#{adminBean.allTabNames}" />
</p:selectManyCheckbox>
<p:commandButton value="Update" id="submit" ajax="true" />
</h:panelGrid>
<br/>
</p:rowExpansion>
----------------update with my own solution (not graceful one, but works) -----
Every time an ajax buttom has been clicked, the whole data table is updated. That means each setSelectedItem method will be called with expected value or empty value. I don't know how to change that.
So I modify my save() method called from ajax button with following logic:
public void save(Long userId, List<String> selectedItem) {
for (User user: users) {
if (user.getId() == userId) {
//update selectedItem in db for this user.
} else {
// read selectedItems in db
// update selectedItem in user object.
}
}
}
When the ajax event is fired, all the input elements in the form are sent. That means that all the selectManyCheckbox (one for each row) are sent. That's why setSelectedTabsNames is called several times.
You have to change how you have designed your implementation. One way woud be to store the selected options in the FopsUser object, so you could do value="#{user.selectedTabsNames}":
<p:selectManyCheckbox id="grid" value="#{user.selectedTabsNames}"
layout="pageDirection" >
**<f:selectItems value="#{adminBean.allTabNames}" />**
</p:selectManyCheckbox>
This way the selected tabs for each row are stored separately.
I may be wrong, but I don't think rowToggle event is the kind of ajax event that can handle row-level parameters. Think about it this way: var="user" is a row-iteration level variable, available for each row in the datatable. The rowToggle event on the other hand is a single level tag, applicable to the entire table as one component. So there probably isn't a reliable way for the datatable to know which row you're referring to when you use
adminBean.onRowToggle(user.id), it'll just select the last row that was rendered
A more effective way to get hold of the details of the row that was toggled is using the ToggleEvent listener in the backing bean, where you don't have to pass a variable:
public void onRowToggle(ToggleEvent te){
User theSelectedUser = (User)te.getData();
int id = theSelectedUser.getId();
}
In your view, you'll now have:
<p:ajax event="rowToggle" listener="#{adminBean.onRowToggle}" update=":form:tabView:form1:growl"/>
I am trying to use filtering on my datatable. Whenever the table first loads, it looks like this:
If I enter text into the filter of user name, the table looks like this:
I would expect it to only show dangreen87 since mike.smith does not contain a "d". It however just displays no user names. Im not sure what this behaviour is?
I have a datatable like so:
<h:body>
<ui:composition>
<h:panelGroup layout="block" styleClass="messagesPanel" rendered="#{socialAdvertiserManagedBean.displaySearch}" >
<p:dataTable
resizableColumns="true"
var="account"
value="#{searchManagedBean.accountsToDisplay}"
scrollable="true"
paginator="true"
rows="10"
rowKey="#{account.id_value}"
emptyMessage="No accounts found for the given criteria"
widgetVar="searchTable"
filteredValue="#{searchManagedBean.filteredAccounts}">
<f:facet name="header">
#{searchManagedBean.isCompany ? 'Company' : 'Social Advertisers'}
</f:facet>
<p:column headerText="Image">
<p:graphicImage value="/dbimages/#{accountManagedBean.getImageId(account)}" width="25" height="25"/>
</p:column>
<c:if test="#{searchManagedBean.isCompany}" >
<p:column headerText="Company Name">
<h:outputLabel value="#{accountManagedBean.getCompany(account).name}" />
</p:column>
</c:if>
<c:if test="#{not searchManagedBean.isCompany}" >
<p:column id="userNameColumn" filterBy="#{account.userName}" filterMatchMode="contains">
<f:facet name="header">
<h:outputLabel value="User Name"/>
</f:facet>
<h:outputLabel value="#{account.userName}" />
</p:column>
</c:if>
</p:dataTable>
My Backing bean looks like so:
#ManagedBean
#ViewScoped
public class SearchManagedBean implements Serializable
{
private boolean isCompany;
private Account selectedAccount;
#EJB
private AccountDao accountDao;
#EJB
private SocialAdvertiserDao socialAdvertiserDao;
#EJB
private CompanyDao companyDao;
private List<Account> filteredAccounts;
#PostConstruct
public void init()
{
isCompany = true;
}
public List<Account> getAccountsToDisplay()
{
List temp;
if(isCompany)
{
temp = companyDao.findAll();
}
else
{
temp = socialAdvertiserDao.findAll();
}
return temp;
}
public List<Account> getFilteredAccounts() {
return filteredAccounts;
}
public void setFilteredAccounts(List<Account> filteredAccounts) {
this.filteredAccounts = filteredAccounts;
}
public boolean getIsCompany() {
return isCompany;
}
public void setIsCompany(boolean isCompany) {
this.isCompany = isCompany;
}
....
Those JSTL <c:if> tags bound to a view scoped bean property is the culprit.
<c:if test="#{not searchManagedBean.isCompany}" >
<p:column id="userNameColumn" filterBy="#{account.userName}" filterMatchMode="contains">
...
</p:column>
</c:if>
Long story short, carefully read #ViewScoped fails in taghandlers and JSTL in JSF2 Facelets... makes sense? In a nutshell, it causes the view scoped bean to be recreated on every single HTTP request and therefore a complete reset of the bean's state across the filtering and sorting ajax requests.
This #ViewScoped+taghandler issue is solved since Mojarra 2.1.18. Basically, you'd need to upgrade to at least Mojarra 2.1.18 (it's currently already at 2.1.25). However, this is after all not the canonical approach. You should just use the rendered attribute of <p:column> for that.
<p:column id="userNameColumn" filterBy="#{account.userName}" filterMatchMode="contains" rendered="#{not searchManagedBean.isCompany}">
...
</p:column>
I have a data table with a couple of rows and I have a column where I have a form with a simple button that deletes the object in that row.
So first the working version:
<h:dataTable value="#{actorTableBackingBean.allActors}"
var="actor" styleClass="table table-bordered">
<h:column headerText="Actor Name" sortBy="#{actor.firstName}">
<h:outputText value="#{actor.firstName}"/>
</h:column>
<h:column headerText="Actor Detail">
<h:form>
<h:commandButton value="Delete Actor"
styleClass="btn btn-primary"
action="#{actorTableBackingBean.deleteActor(actor.actorId)}"/>
</h:form>
</h:column>
</h:dataTable>
And this is what deleteActor method looks like:
public String deleteActor(String id){
removeActorWithId(id);
return "/allActors.xhtml";
}
private void removeActorWithId(String id){
int idk = Integer.parseInt(id);
for(Actor a:allActors){
if(a.getActorId() == idk){
allActors.remove(a);
return;
}
}
}
So this exactly works as expected as it is.
However, when I use a Pagination Data table of Primefaces as shown in here, delete button works only for the FIRST ROW in the second case and only for the first time.
When I click on button "Delete" for other rows, simply nothing happens.
What might be the reason?
For second situation just put the < form > tags around p:dataTable as seen in the link and replace everything like h:dataTable to p:dataTable and p:column etc...
I would suggest that you make the form tag contain your datatable.
This works:
<h:form id="actorsTableForm">
<p:dataTable id="actorsTable" var="item"
value="#{actorsMB.actorList}" selectionMode="single"
rowKey="#{item.description}" paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" paginatorPosition="bottom">
<p:column headerText="Actor Id" >
<h:outputText value="#{item.id}" />
</p:column>
<p:column headerText="Actor Description">
<h:outputText value="#{item.description}" />
</p:column>
<p:column>
<p:commandButton icon="ui-icon-trash"
title="Delete this actor"
actionListener="#{actorsMB.remove(item)}"
ajax="false" />
</p:column>
</p:dataTable>
</h:form>
And the method in the managed bean:
public void remove(Actor actor) {
try {
actorService.remove(actor);
actorList = actorService.searchAll();
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it helps.
Following code might help you.
Your xhtml code should be like this
<h:form>
<h:dataTable value="#{actorTableBackingBean.allActors}"
binding="#{actorTableBackingBean.dataTable}"
var="actor" styleClass="table table-bordered">
<h:column headerText="Actor Name" sortBy="#{actor.firstName}">
<h:outputText value="#{actor.firstName}"/>
</h:column>
<h:column headerText="Actor Detail">
<h:commandButton value="Delete Actor"
styleClass="btn btn-primary"
action="#{actorTableBackingBean.deleteActor}"/>
</h:column>
</h:dataTable>
</h:form>
You have to add one DataTable variable in bean file
private javax.faces.component.html.HtmlDataTable dataTable;
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
Your delete method should be like this
public String deleteActor(){
Actor model = (Actor) dataTable.getRowData();
removeActorWithId(model);
return "/allActors.xhtml";
}
private void removeActorWithId(Actor model){
if(model!=null){
allActors.remove(model);
}
}