目标是在用户过滤数据表时自动选择数据表的第一行。 实现PostFilter事件是为了选择第一行,但实际上它被事后发生的事件覆盖并重新设置初始选定行。
<h:form id="customerForm">
<p:commandButton value="selection change" action="#{customerControllerv1.selectionChange}"/>
<p:commandButton value="selection show" action="#{customerControllerv1.selectionShow}"/>
<p:dataTable id="dtCustomer" var="customer" value="#{customerControllerv1.customers}" rowKey="#{customer.id}"
selection="#{customerControllerv1.selectedCustomer}" selectionMode="single"
binding="#{customerControllerv1.uiCustomers}">
<f:event type="org.primefaces.event.data.PostFilterEvent" listener="#{customerControllerv1.postFilter()}" />
<p:column headerText="Id">
<h:outputText value="#{customer.id}" />
</p:column>
<p:column headerText="First Name" filterBy="#{customer.firstName}" filterMatchMode="contains" >
<h:outputText value="#{customer.firstName}" />
</p:column>
<p:column headerText="Last Name" filterBy="#{customer.lastName}" filterMatchMode="contains">
<h:outputText value="#{customer.lastName}" />
</p:column>
</p:dataTable>
</h:form>
@ManagedBean(name = "customerControllerv1")
@ViewScoped
public class CustomerControllerv1 implements Serializable {
private static final long serialVersionUID = 1L;
private Customer selectedCustomer;
private DataTable uiCustomers;
private List<Customer> customers = new ArrayList<Customer>();
public CustomerControllerv1() {
}
@PostConstruct
void init() {
CustomerDAO custDAO = new CustomerDAO();
customers = custDAO.getAllCustomers();
// select first row
if (customers.size()>0) selectedCustomer=customers.get(0);
}
public void postFilter () {
selectionChange();
}
public void selectionChange () {
RequestContext context = RequestContext.getCurrentInstance();
List<Customer> sortedList = (List<Customer>)uiCustomers.getValue();
// select first row of the filtered list and render the DataTable
if (sortedList.size()>0) selectedCustomer=sortedList.get(0);
context.update("customerForm:dtCustomer");
}
public void selectionShow () {
System.out.println( "selectionShow: "+selectedCustomer.getId() );
}
// getters and setters
....
}
有没有人知道如何解决这个问题?