Grid sorting is not working for me

Hi,

I’m trying to use Vaadin 8 (8.1.5) framework as I have used 7 before. I’ve created my project in the same way that I did with the previous version (using maven archetype in Eclipse - vaadin-archetype-application-example). But now the grid sorting is not working properly (even the ProductGrid class provided by the CRUD example). Can you help me please?

Follow the code:

import com.project.testvaadin8.samples.backend.data.Account;
import com.vaadin.ui.Grid;

public class SimpleGrid extends Grid<Account> {
    
    public SimpleGrid() {
        setSizeFull();
        
        addColumn(Account::getAccount).setCaption("Account");
        addColumn(Account::getBank).setCaption("Bank");
        addColumn(Account::getCurrency).setCaption("Currency");
        
        //setSortOrder(GridSortOrder.desc(getColumn("account")));
    }

By default Grid sorts by the toString() presentation of your property. If this does not provide desired result (which is often the case with dates etc.), you need to set custom comparator wíth setSortComparator(…) method of the ListDataProvider.

Hi Tatu,

all my data fields are just Strings, like these:

[code]
public class Account implements Serializable {

private String accountNumber;
private String bankCode;
private BigDecimal ammount;

public Account(String accountNumber, String bankCode) {
    this.accountNumber = accountNumber;
    this.bankCode = bankCode;
}

}
[/code]And the form component look like this:

    protected void init(VaadinRequest vaadinRequest) {
        
        final VerticalLayout layout = new VerticalLayout();
        final HorizontalLayout hLayout = new HorizontalLayout();
        
        final TextField accountNumber = new TextField();
        accountNumber.setCaption("Account Number");
        
        final TextField bankCode = new TextField();
        bankCode.setCaption("Bank Code");

        final Button addButton = new Button("Add Account");
        addButton.setStyleName(ValoTheme.BUTTON_PRIMARY);
        addButton.addClickListener(e -> {
            service.save(new Account(accountNumber.getValue(), bankCode.getValue()));
            dataProvider.refreshAll();
        });
        
        hLayout.addComponents(accountNumber, bankCode, addButton);

        final Grid<Account> accountsGrid = new Grid<>(Account.class);
        accountsGrid.setDataProvider(dataProvider);
        accountsGrid.setSizeFull();

        layout.addComponents(hLayout, accountsGrid);
        layout.setSizeFull();
        layout.setExpandRatio(accountsGrid, 1.0f);

        setContent(layout);
    }

I found what was wrong! When we are using DataProvider it is necessary to create our own sort implementation. I just changed to this approach:

accountsGrid.setItems(service.findAll)

and then the sort feature is working again!