Search code examples
gridvaadin8vaadin-flowcolumnsortingvaadin-grid

Sort vaadin grid containing text field as component column


I am using vaadin 8. This grid contains a number of columns. Two columns are having textfield as component column because user wants to enter something in string format. Hence we use TextField component inside both columns. This is done by using grid.addComponentColumn method. Even after enabling setSorting(true), it seems that sorting is not working for both these columns.

    addComponentColumn(DataGrid::getUserMessage).setId("userMessage").setSortable(true).setCaption("UserMessage");

i have tried below two things but still it is not sorting.

First

addComponentColumn(DataGrid::getUserMessage).setId("userMessage").setSortable(true).setCaption("UserMessage").setComparator((p1, p2) -> p1.getUserMessage().getValue().compareTo(p2.getUserMessage().getValue()));

Second

addComponentColumn(DataGrid::getUserMessage).setId("userMessage").setSortable(true).setCaption("UserMessage").setSortOrderProvider(direction -> Arrays.asList(new QuerySortOrder("userMessage", direction)).stream());

Data grid is the class which contains column names and its setter/getters. How can I make this work? Can someone demonstrate it by a snippet

Update below solution works! This piece of code is for improvement for sorting containin null values while using comparator

    @Override
    public int compare(final DataGrid a, final DataGrid b) {
        if (a.getUserMessage().getIntegerValue() == null && b.getUserMessage().getIntegerValue() == null) {
            return 0;
        }
        if (a.getUserMessage().getIntegerValue() == null) {
            return -1;
        }
        if (b.getUserMessage().getIntegerValue() == null) {
            return 1;
        }
        return a.getUserMessage().getIntegerValue().compareTo(b.getUserMessage().getIntegerValue());
    }
);```

Solution

  • Here is a minimal example,

    List<Person> personList = new ArrayList<>();
    personList.add(new Person("Lucas", "Lucas Message"));
    personList.add(new Person("Samuel", "Samuel Message"));
    personList.add(new Person("Aaron", "Aaron Message"));
    
    Grid<Person> grid = new Grid<>();
    grid.setItems(personList);
    
    grid.addColumn(Person::getName).setCaption("Name");
    
    grid.addComponentColumn(person -> {
        TextField tf = new TextField();
        tf.setValue(person.getMessage());
        tf.addValueChangeListener(e -> {
            person.setMessage(e.getValue());
        });
        return tf;
    }).setId("customColumn").setComparator(
            (p1, p2) -> p1.getMessage().compareTo(p2.getMessage()))
            .setCaption("Message");
    


    And the Person class

    public class Person {
    
        private String name;
        private String message;
    
        public Person(String name, String message) {
            setName(name);
            setMessage(message);
        }
    
        // Getters and Setters
    }