David Marko
David Marko

Reputation: 2519

Vaadin Grid and initially sorted data

I have a Grid component with Indexed container where data is sorted initially into two columns (the data comes from Elasticsearch). How can I tell Grid to know about this sorting and then show proper sorting icons in column headings when Grid is loaded?

EDIT #1 I tried to redefine Grids public List<SortOrder> getSortOrder() method to return proper sorting data, but it doesnt work ...

Upvotes: 1

Views: 4654

Answers (1)

Morfic
Morfic

Reputation: 15508

You haven't shown much code so I'll have to assume you're using the default Indexed container and then add columns like grid.addColumn("c1", String.class);. If that's true, then it looks like you can't supply your own container implementation because vaadin will throw an exception when providing a different container and adding columns (haven't had the time to figure out why):

protected void addColumnProperty(Object propertyId, Class<?> type, Object defaultValue) throws IllegalStateException {
    if(!this.defaultContainer) {
        throw new IllegalStateException("Container for this Grid is not a default container from Grid() constructor");

In this case, you can probably create your own Grid implementation which bypasses the issue, or you could use a bean item container like in the example below, where you overwrite the doSort method to do nothing:

BeanItemContainer<MyBean> dataSource = new BeanItemContainer<MyBean>(MyBean.class) {
    @Override
    protected void doSort() {
        // nop, data is already sorted
    }
};
Grid grid = new Grid(dataSource);

Then simply call the setSortOrder method on the grid.

import com.vaadin.data.sort.Sort;
import com.vaadin.shared.data.sort.SortDirection;
...
grid.setSortOrder(Sort.by("c3", SortDirection.ASCENDING).then("c2", SortDirection.DESCENDING).build());

Which results in column c3 being sorted ascending first, and then c2 descending (see the numbers near the sorting icon):

sorting sample

Please note that the column headers will still be clickable so the sorting icons will change and events will be triggered, but nothing will happen because the doSort was overwritten. You will probably need to react to this so you can add a sortListener and request a new batch of data, sorted according to the user selection:

grid.addSortListener(new SortEvent.SortListener() {
    @Override
    public void sort(SortEvent sortEvent) {
        // request data sorted according to the user selection
    }
});

Upvotes: 1

Related Questions