How to handle error in Primefaces lazy load?

隐身守侯 提交于 2019-12-05 16:40:25

It doesn't work because load() method is invoked during Render Response phase (you can check this by printing FacesContext.getCurrentInstance().getCurrentPhaseId()), when all messages have already been processed.

The only workaround that worked for me is to load the data within the "page" event listener of the DataTable.

html:

<p:dataTable value="#{controller.model}" binding="#{controller.table}">
     <p:ajax event="page" listener="#{controller.onPagination}" />
</p:dataTable>

Controller:

private List<DTO> listDTO;
private int rowCount;
private DataTable table;

private LazyDataModel<DTO> model = new LazyDataModel<DTO>() {
        @Override
        public List<DTO> load(int first, int pageSize, String sortField,
                SortOrder sortOrder, Map<String, String> filters) {
            setRowCount(rowCount);
            return listDTO;
        }
    };

public void onPagination(PageEvent event) {
    FacesContext ctx = FacesContext.getCurrentInstance();
    Map<String, String> params = ctx.getExternalContext()
            .getRequestParameterMap();

    // You cannot use DataTable.getRows() and DataTable.getFirst() here,
    // it seems that these fields are set during Render Response phase
    // and not during Update Model phase as one can expect.

    String clientId = table.getClientId();
    int first = Integer.parseInt(params.get(clientId + "_first"));
    int pageSize = Integer.parseInt(params.get(clientId + "_rows"));

    try {
        listDTO = DAO.query(first, pageSize);
        rowCount = DAO.getRowCount();
    } catch (SQLException e) {
        ctx.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "SQL error",
                    "SQL error"));
    }
}

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!