Подтвердить что ты не робот

Невозможно установить начальный порядок сортировки для DataTable программно

Мне нужно установить sortBy для DataTable программным путем bean. DataTable имеет один режим сортировки, статические столбцы и пользовательскую ленивую модель для сортировки по пользовательским выражениям типа = "# {contractor.companyName-MULTY_LANG}". Я пробовал много способов сделать это, и только один способ работает (код ниже), но работает не правильно - компонент показан без выделенного упорядоченного поля. Может ли кто-нибудь ответить, как правильно выбрать метод sortBy для DataTable программно?

@PostConstruct
    public void init() {    
        final DataTable d = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent(TABLE_COMPONENT_KEY);
        String tableSortByExpression = "#{contractor.companyName-MULTY_LANG}"; // expression from some column
        SortMeta sm1 = new SortMeta();
        for (UIComponent child : d.getChildren()) {
            Column column = (Column)child;
            ValueExpression columnSortByVe = column.getValueExpression("sortBy");
            if (columnSortByVe != null) {
                String columnSortByExpression = columnSortByVe.getExpressionString();
                if (tableSortByExpression != null && tableSortByExpression.equals(columnSortByExpression)) {
                    d.setSortColumn(column);
                    d.setSortOrder("ASCENDING");
                    break;
                }
            }
        }
    }

Буду признателен за любую помощь.


Графики 5.1. Tomcat 7. Mojarra 2.2.8

4b9b3361

Ответ 1

Прежде всего, расширьте org.primefaces.component.datatable.feature.SortFeature

public class CustomSortFeature extends SortFeature {
    @SuppressWarnings("rawtypes")
    @Override
    public void encode(FacesContext context, DataTableRenderer renderer, DataTable table) throws IOException {
        table.setFirst(0);

        if(table.isLazy()) {
            table.loadLazyData();
            singleSort(context, table);
        }
        else {
            if(table.isMultiSort())
                multiSort(context, table);
            else
                singleSort(context, table);

            if(table.isPaginator()) {
                RequestContext requestContext = RequestContext.getCurrentInstance();

                if(requestContext != null) {
                    requestContext.addCallbackParam("totalRecords", table.getRowCount());
                }
            }

            //save state
            Object filteredValue = table.getFilteredValue();
            if(!table.isLazy() && table.isFilteringEnabled() && filteredValue != null) {
                table.updateFilteredValue(context, (List) filteredValue);
            }
        }

        renderer.encodeTbody(context, table, true);
    }
}

Затем попробуйте расширить org.primefaces.component.datatable.DataTableRenderer

@FacesRenderer(componentFamily = "org.primefaces.component", rendererType = "org.primefaces.component.DataTableRenderer")
public class CustomDataTableRenderer extends DataTableRenderer {
    public List<DataTableFeatureKey> FEATURE = new ArrayList<DataTableFeatureKey>(){/**
         * 
         */
        private static final long serialVersionUID = 1L;

    {
        add(DataTableFeatureKey.DRAGGABLE_COLUMNS);
        add(DataTableFeatureKey.FILTER);
        add(DataTableFeatureKey.PAGE);
        add(DataTableFeatureKey.SORT);
        add(DataTableFeatureKey.RESIZABLE_COLUMNS);
        add(DataTableFeatureKey.SELECT);
        add(DataTableFeatureKey.ROW_EDIT);
        add(DataTableFeatureKey.CELL_EDIT);
        add(DataTableFeatureKey.ROW_EXPAND);
        add(DataTableFeatureKey.SCROLL);
        add(DataTableFeatureKey.DRAGGABLE_ROWS);
    }};
    @Override
    protected void preRender(FacesContext context, DataTable table){
        table.setCaseSensitiveSort(false);
        if(table.isLazy()) {
            if(table.isLiveScroll())
                table.loadLazyScrollData(0, table.getScrollRows());
            else
                table.loadLazyData();
        }

        boolean defaultSorted = (table.getValueExpression("sortBy") != null || table.getSortBy() != null);
        if(defaultSorted && !table.isLazy()) {
            table.setDefaultSortByVE(table.getValueExpression("sortBy"));
            table.setDefaultSortOrder(table.getSortOrder());
            table.setDefaultSortFunction(table.getSortFunction());

            CustomSortFeature sortFeature = (CustomSortFeature) table.getFeature(DataTableFeatureKey.SORT);

            if(table.isMultiSort())
                sortFeature.multiSort(context, table);
            else
                sortFeature.singleSort(context, table);  

            table.setRowIndex(-1);
        }

        if(table.isPaginator()) {
            table.calculateFirst();
        }

        Columns dynamicCols = table.getDynamicColumns();
        if(dynamicCols != null) {
            dynamicCols.setRowIndex(-1);
        }
    }

    @Override
    public void encodeEnd(FacesContext context, UIComponent component) throws IOException{
        DataTable table = (DataTable) component;
        if(table.shouldEncodeFeature(context)) {
            for(Iterator<DataTableFeatureKey> it = FEATURE.iterator(); it.hasNext();) {
                DataTableFeature feature = table.getFeature(it.next());

                if(feature.shouldEncode(context, table)) {
                    feature.encode(context, this, table);
                }
            }
        }
        else {  
            preRender(context, table);

            encodeMarkup(context, table);
            encodeScript(context, table);
        }
    }
}

Кроме того, добавьте класс render в faces-config

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
        <render-kit>
            <renderer>
                <component-family>org.primefaces.component</component-family>
                <renderer-type>org.primefaces.component.DataTableRenderer</renderer-type>
                <renderer-class>com.edtoktay.CustomDataTableRenderer</renderer-class>
            </renderer>
        </render-kit>
</faces-config>

Надеюсь, что это поможет