Grid

The Grid component allows you to display and edit tabular data, set out in rows and columns.

The component is included in this documentation as a good example of a complex component, which is highly flexible yet simple to use, and offers a lot of functionality out of the box.

Grid features include:

  • Header and footer: In addition to plain text, the header and footer can contain components. Allowing components makes it easy to implement additional functionality, such as filtering.

  • Sorting: Column sorting is built in. Users can click the column header to sort the data, and shift click to enable secondary sorting criteria.

  • Scrolling: The data area can be scrolled both vertically and horizontally. You can freeze the left columns to keep them in view when scrolling horizontally.

  • Lazy loading: The data is loaded lazily from the server: only visible data is actually loaded. This provides an excellent user experience, even for low bandwidth devices, such as mobile phones.

Binding to Data

By default, Grid is bound to a List of items. You can use the setItems() method to set the items.

Example: Showing a list of beans in a Grid.

Java

  1. // Have some data
  2. List<Person> people = Arrays.asList(
  3. new Person("Nicolaus Copernicus", 1543),
  4. new Person("Galileo Galilei", 1564),
  5. new Person("Johannes Kepler", 1571));
  6. // Create a grid bound to the list
  7. Grid<Person> grid = new Grid<>();
  8. grid.setItems(people);
  9. grid.addColumn(Person::getName).setHeader("Name");
  10. grid.addColumn(Person::getYearOfBirth)
  11. .setHeader("Year of birth");
  12. layout.add(grid);

Behind the scenes Grid uses the DataProvider interface to communicate with the backend. The setItems method is a shorthand to create a ListDataProvider. For a large amount of data or other advanced use cases you should probably use the DataProvider interface and lazy loading. See Data Providers for more.

Handling Selection Changes

The Grid doesn’t implement the HasValue interface directly. Other selection components do typically implement this interface. For this reason, selection handling in the Grid is different from typical selection components. The Grid supports three selection options: single selection, multiple selection, and no selection. Each option is defined by a specific selection model.

For basic switching between selection models, you can use the setSelectionMode(SelectionMode) method. Possible options are SINGLE (default), MULTI, or NONE.

To access the selection API or to use Grid as an input field with Binder, you can use asSingleSelect() or asMultiSelect(), depending on the currently defined selection mode. Both the SingleSelect and MultiSelect interfaces implement the HasValue interface. In the MultiSelect interface the value type is a Set of the item type.

Example: Using the HasValue interface with single and multi-select mode.

Java

  1. Grid<Person> grid = new Grid<>();
  2. grid.setSelectionMode(SelectionMode.SINGLE);
  3. SingleSelect<Grid<Person>, Person> personSelect =
  4. grid.asSingleSelect();
  5. // personSelect can now be used with Binder or
  6. // HasValue interface
  7. personSelect.addValueChangeListener(e -> {
  8. Person selectedPerson = e.getValue();
  9. });
  10. grid.setSelectionMode(SelectionMode.MULTI);
  11. MultiSelect<Grid<Person>, Person> multiSelect =
  12. grid.asMultiSelect();
  13. multiSelect.addValueChangeListener(e -> {
  14. Set<Person> selectedPersons = e.getValue();
  15. });

Alternatively you can use a grid-specific selection API. To get the selected value or values in any selection model, you can use a SelectionListener, with the provided generic SelectionEvent, to get the selected value or values.

Example: Using addSelectionListener to get all selected items.

Java

  1. Grid<Person> grid = new Grid<>();
  2. // switch to multiselect mode
  3. grid.setSelectionMode(SelectionMode.MULTI);
  4. grid.addSelectionListener(event -> {
  5. Set<Person> selected = event.getAllSelectedItems();
  6. message.setText(selected.size() + " items selected");
  7. });
Note
The listener is attached to the selection model and not the grid. It stops getting events when the selection mode is changed.

You can use the select(T) method to programmatically select values. In multi-selection mode, this adds the given item to the selection.

Example: Using the select(T) method.

Java

  1. // in single-select, only one item is selected
  2. grid.select(defaultItem);
  3. // switch to multi select, clears selection
  4. grid.setSelectionMode(SelectionMode.MULTI);
  5. // Select items 2-4
  6. people.subList(2, 3).forEach(grid::select);

You can get the current selection from the Grid using the getSelectedItems() method. The returned Set contains one item in single-selection mode, or several items in multi-selection mode.

Warning

If you change the grid’s selection mode, it clears the selection and fires a selection event. To keep the previous selection, reset the selection afterwards, using the select() method.

Warning

If you change the grid’s items with either setItems() or the used DataProvider, it clears the selection and fires a selection event. To retain the previous selection, reset the selection afterwards, using the select() method.

Selection Models

You can access the used selection model using the getSelectionModel() method. The return type is the GridSelectionModel that has a generic selection model API, but you can cast that to the specific selection model type, typically either SingleSelectionModel or MultiSelectionModel.

You can also get the selection model using the setSelectionMode(SelectionMode) method.

Example: Using the setSelectionMode(SelectionMode) method to get the selection model.

Java

  1. // the default selection model
  2. GridSingleSelectionModel<Person> defaultModel =
  3. (GridSingleSelectionModel<Person>) grid
  4. .getSelectionModel();
  5. // Use multi-selection mode
  6. GridMultiSelectionModel<Person> selectionModel =
  7. (GridMultiSelectionModel<Person>) grid
  8. .setSelectionMode(SelectionMode.MULTI);

Single-selection Model

Obtaining a reference to the SingleSelectionModel allows you access to a fine-grained API for the single-selection use case.

You can use the addSingleSelect(SingleSelectionListener) method to access SingleSelectionEvent that includes additional convenience methods and API options.

In single-selection mode, it is possible to control whether the empty (null) selection is allowed. This is enabled by default.

Example: Disallowing empty (null) selection using the setDeselectAllowed() method.

Java

  1. // preselect value
  2. grid.select(defaultItem);
  3. GridSingleSelectionModel<Person> singleSelect =
  4. (GridSingleSelectionModel<Person>) grid
  5. .getSelectionModel();
  6. // disallow empty selection
  7. singleSelect.setDeselectAllowed(false);

Multi-selection Model

In multi-selection mode, a user can select multiple items by selecting checkboxes in the left column.

Obtaining a reference to the MultiSelectionModel allows you access to a fine-grained API for the multi-selection use case.

You can use the addMultiSelectionListener(MultiSelectionListener) method to access MultiSelectionEvent that includes additional convenience methods and API options.

Example: Using the addMultiSelectionListener method to access selection changes.

Java

  1. // Grid in multi-selection mode
  2. Grid<Person> grid = new Grid<>();
  3. grid.setItems(people);
  4. GridMultiSelectionModel<Person> selectionModel =
  5. (GridMultiSelectionModel<Person>) grid
  6. .setSelectionMode(SelectionMode.MULTI);
  7. selectionModel.selectAll();
  8. selectionModel.addMultiSelectionListener(event -> {
  9. message.setText(String.format(
  10. "%s items added, %s removed.",
  11. event.getAddedSelection().size(),
  12. event.getRemovedSelection().size()));
  13. // Allow deleting only if there's any selected
  14. deleteSelected.setEnabled(
  15. event.getNewSelection().isEmpty());
  16. });

Handling Item-click Events

It is possible to handle item-click or double-click events, in addition to handling selection events. These can be used with selection events or on their own.

Example: Disabling the selection mode using SelectionMode.NONE, but still getting item-click events.

Java

  1. grid.setSelectionMode(SelectionMode.NONE);
  2. grid.addItemClickListener(event -> System.out
  3. .println(("Clicked Item: " + event.getItem())));
  • The clicked item, together with other information about click, is available via the event.

  • Selection events are no longer available, and no visual selection is displayed when a row is clicked.

It is possible to get separate selection and click events.

Example: Using Grid in multi-selection mode with an added click (or double-click) listener.

Java

  1. grid.setSelectionMode(SelectionMode.MULTI);
  2. grid.addItemDoubleClickListener(event ->
  3. copy(grid.getSelectedItems()));
  • In the example code, we call a local copy method with the currently selected items when user double clicks a row.

Configuring Columns

The addColumn() method allows you to add columns to the Grid.

The column configuration is defined in Grid.Column objects that are returned by the addColumn method. The getColumns() method returns a list of currently configured columns.

The setter methods in Column have fluent-API functionality, making it easy to chain configuration calls for columns.

Example: Chaining column configuration calls.

Java

  1. Column<Person> nameColumn = grid
  2. .addColumn(Person::getName)
  3. .setHeader("Name")
  4. .setFlexGrow(0)
  5. .setWidth("100px")
  6. .setResizable(false);

Column Keys

You can set an identifier key for a column using the setKey() method. This allows you to retrieve the column from the grid at any time.

Example: Using the setKey method to set an identifier key for a column.

Java

  1. nameColumn.setKey("name");
  2. grid.getColumnByKey("name").setWidth("100px");

Automatically Adding Columns

You can configure Grid to automatically add columns for every property in a bean, by passing the class of the bean type to the grid’s constructor. The property names are set as the column keys, and you can use them to further configure the columns.

Example: Automatically adding columns by passing the bean-type class to the constructor.

Java

  1. Grid<Person> grid = new Grid<>(Person.class);
  2. grid.getColumnByKey("yearOfBirth").setFrozen(true);
  • This constructor only adds columns for the direct properties of the bean type

  • The values are displayed as strings.

You can add columns for nested properties by using the dot notation with the setColumn(String) method.

Example: Adding a column for postalCode. Assumes Person has a reference to an Address object that has a postalCode property.

Java

  1. grid.addColumn("address.postalCode");
  • The column’s key is “address.postalCode” and its header is “Postal Code”.

  • To use these String properties in addColumn, you need to use the Grid constructor that takes a bean-class parameter.

Defining and Ordering Automatically-Added Columns

You can define which columns display, and the order in which they disaply, in the grid, using the setColumns method.

Example: Defining columns and their order using the setColumns method.

Java

  1. Grid<Person> grid = new Grid<>(Person.class);
  2. grid.setColumns("name", "age", "address.postalCode");
Tip
You can also use the setColumns method to reorder the columns you already have.
Note
When calling setColumns, all columns that are currently present in the grid are removed, and only those passed as parameters are added.

To add custom columns before the auto-generated columns, use the addColumns method instead. You can avoid creating the auto-generated columns using the Grid(Class, boolean) constructor.

Example: Adding custom columns.

Java

  1. Grid<Person> grid = new Grid<>(Person.class, false);
  2. grid.addColumn(person -> person.getName().split(" ")[0])
  3. .setHeader("First name");
  4. grid.addColumns("age", "address.postalCode");
Note
An IllegalArgumentException is thrown if you attempt to add columns that are already present the grid.

Sortable Automatic Columns

By default, all property-based columns are sortable, if the property type implements Comparable.

Many data types, such as String, Number, primitive types and Date/LocalDate/LocalDateTime are Comparable, and therefore also sortable, by default.

To make the column of a non-comparable property type sortable, you need to define a custom Comparator. See Column Sorting for more.

You can disable sorting for a specific column, using the setSortable method.

Example: Disabling sorting on the address.postalCode column.

Java

  1. grid.getColumnByKey("address.postalCode")
  2. .setSortable(false);

You can also define a list of columns as sortable using the setSortableColumns method. This makes all other columns unsortable.

Example: Setting defined columns as sortable.

Java

  1. // All columns except "name" and "yearOfBirth"
  2. // will be not sortable
  3. grid.setSortableColumns("name", "yearOfBirth");

Column Headers and Footers

By default, columns do not have a header or footer. These need to be set explicitly using the setHeader and setFooter methods. Both methods have two overloads: one accepts a plain text string and the other a TemplateRenderer.

Examples: Setting headers and footers.

Java

  1. // Sets a simple text header
  2. nameColumn.setHeader("Name");
  3. // Sets a header using Html component,
  4. // in this case simply bolding the caption "Name"
  5. nameColumn.setHeader(new Html("<b>Name</b>"));
  6. // Similarly for the footer
  7. nameColumn.setFooter("Name");
  8. nameColumn.setFooter(new Html("<b>Name</b>"));

See Using Template Renderers for more.

Column Reordering

Column reordering is not enabled by default. You can use the setColumnReorderingAllowed() method to allow drag and drop column reordering.

Example: Enabling column reordering.

Java

  1. grid.setColumnReorderingAllowed(true);

Hiding Columns

Columns can be hidden by calling the setVisible() method in Column.

Note
A hidden column still sends the data required for its rendering to the client side. Best practice is to remove (or not add) columns, if the data is not needed on the client side. This reduces the amount of data sent and lessens the load on the client.

Removing Columns

You can remove a single column using the removeColumn(Column) and removeColumnByKey(String) methods. You can also remove all currently configured columns using the removeAllColumns() method.

Setting Column Widths

By default, columns do not have a defined width. They resize automatically based on the data displayed.

You can set the column width:

  • Relatively, using flex grow ratios, by using the setFlexGrow() method, or

  • Explicitly, using a CSS string value with setWidth() (with flex grow set to 0).

You can also enable user column resizing using the setResizable() method. The column is resized by dragging the column separator.

Setting Frozen Columns

You can freeze a number of columns using the setFrozen() method. This ensures that the set number of columns on the left remain static (and visible) when the user scrolls horizontally.

When columns are frozen, user reordering is limited to only among other frozen columns.

Example: Setting a column as frozen.

Java

  1. nameColumn.setFrozen(true);

Grouping Columns

You can group multiple columns together by adding them in the HeaderRow of the grid.

When you retrieve the HeaderRow, using the prependHeaderRow or appendHeaderRow methods, you can then group the columns using the join method. In addition, you can use the setText and setComponent methods on the join result to set the text or component for the joined columns.

Example: Grouping columns

Java

  1. // Create a header row
  2. HeaderRow topRow = grid.prependHeaderRow();
  3. // group two columns under the same label
  4. topRow.join(nameColumn, ageColumn)
  5. .setComponent(new Label("Basic Information"));
  6. // group the other two columns in the same header row
  7. topRow.join(streetColumn, postalCodeColumn)
  8. .setComponent(new Label("Address Information"));

Using Renderers in Columns

You can configure columns to use a renderer to show the data in the cells.

Conceptually, there are three types of renderer:

  1. Basic renderer: Renders basic values, such as dates and numbers.

  2. Template renderer: Renders content using HTML markup and Polymer data-binding syntax.

  3. Component renderer: Renders content using arbitrary components.

Using Basic Renderers

There are several basic renderers that you can use to configure grid columns.

Local Date Renderer

Use LocalDateRenderer to render LocalDate objects in the cells.

Example: Using LocalDateRenderer with the addColumn method.

Java

  1. grid.addColumn(new LocalDateRenderer<>(
  2. Item::getEstimatedDeliveryDate,
  3. DateTimeFormatter.ofLocalizedDate(
  4. FormatStyle.MEDIUM)))
  5. .setHeader("Estimated delivery date");

LocalDateRenderer works with a DateTimeFormatter or a String format to properly render LocalDate objects.

Example: Using a String format to render the LocalDate object.

Java

  1. grid.addColumn(new LocalDateRenderer<>(
  2. Item::getEstimatedDeliveryDate,
  3. "dd/MM/yyyy"))
  4. .setHeader("Estimated delivery date");

Local Date Time Renderer

Use LocalDateTimeRenderer to render LocalDateTime objects in the cells.

Example: Using LocalDateTimeRenderer with the addColumn method.

Java

  1. grid.addColumn(new LocalDateTimeRenderer<>(
  2. Item::getPurchaseDate,
  3. DateTimeFormatter.ofLocalizedDateTime(
  4. FormatStyle.SHORT,
  5. FormatStyle.MEDIUM)))
  6. .setHeader("Purchase date and time");

LocalDateTimeRenderer also works with DateTimeFormatter (with separate style for date and time) or a String format to properly render LocalDateTime objects.

Example: Using a String format to render the LocalDateTime object.

Java

  1. grid.addColumn(new LocalDateTimeRenderer<>(
  2. Item::getPurchaseDate,
  3. "dd/MM HH:mm:ss")
  4. ).setHeader("Purchase date and time");

Number Renderer

Use NumberRenderer to render any type of Number in the cells. It is especially useful for rendering floating-point values.

Example: Using NumberRenderer with the addColumn method.

Java

  1. grid.addColumn(new NumberRenderer<>(Item::getPrice,
  2. NumberFormat.getCurrencyInstance())
  3. ).setHeader("Price");

It is possible to setup the NumberRenderer with a String format, and an optional null representation.

Example: Using a String format to render a price.

Java

  1. grid.addColumn(new NumberRenderer<>(
  2. Item::getPrice, "$ %(,.2f",
  3. Locale.US, "$ 0.00")
  4. ).setHeader("Price");

Native Button Renderer

Use NativeButtonRenderer to create a clickable button in the cells. It creates a native <button> on the client side. Click and tap (for touch devices) events are handled on the server side.

Example: Using NativeButtonRenderer with the addColumn method.

Java

  1. grid.addColumn(
  2. new NativeButtonRenderer<>("Remove item",
  3. clickedItem -> {
  4. // remove the item
  5. })
  6. );

You can configure a custom label for each item.

Example: Configuring NativeButtonRenderer to use a custom label.

Java

  1. grid.addColumn(new NativeButtonRenderer<>(
  2. item -> "Remove " + item,
  3. clickedItem -> {
  4. // remove the item
  5. })
  6. );

Using Template Renderers

Providing a TemplateRenderer for a column allows you to define the content of cells using HTML markup, and to use Polymer notations for data binding and event handling.

Example: Using TemplateRenderer to bold the names of the persons.

Java

  1. Grid<Person> grid = new Grid<>();
  2. grid.setItems(people);
  3. grid.addColumn(TemplateRenderer
  4. .<Person>of("<b>[[item.name]]</b>")
  5. .withProperty("name", Person::getName)
  6. ).setHeader("Name");
  • The template string is passed for the static TemplateRenderer.of() method.

  • Every property in the template needs to be defined in the withProperty() method.

  • [[item.name]] is Polymer syntax for binding properties for a list of items. See the Polymer 3 documentation for more.

Creating Custom Properties

You can use a TemplateRenderer to create and display new properties (i.e. properties the item did not originally contain).

Example: Using TemplateRenderer to compute the approximate age of each person and add it in a new column. Age is the current year less the birth year.

Java

  1. grid.addColumn(TemplateRenderer
  2. .<Person>of("[[item.age]] years old")
  3. .withProperty("age",
  4. person -> Year.now().getValue()
  5. - person.getYearOfBirth())
  6. ).setHeader("Age");

Binding Beans

If an object contains a bean property that has sub properties, it is only necessary to make the bean accessible by calling the withProperty() method. The sub properties become accessible automatically.

Example: Using the withProperty() method to access numerous sub properties. Assumes Person has a field for the Address bean, which has street, number and postalCode fields with corresponding getter and setter methods.

Java

  1. grid.addColumn(TemplateRenderer.<Person>of(
  2. "<div>[[item.address.street]], number " +
  3. "[[item.address.number]]<br>" +
  4. "<small>[[item.address.postalCode]]</small>" +
  5. "</div>")
  6. .withProperty("address", Person::getAddress))
  7. .setHeader("Address");

Handling Events

You can define event handlers for the elements in your template, and hook them to server-side code, by calling the withEventHandler() method on your TemplateRenderer. This is useful for editing items in the grid.

Example: Using the withEventHandler() method to map defined method names to server-side code. The snippet adds a new column with two buttons: one to edit a property of the item and one to remove the item. Both buttons define a method to call for on-click events.

Java

  1. grid.addColumn(TemplateRenderer.<Person>of(
  2. "<button on-click='handleUpdate'>Update</button>" +
  3. "<button on-click='handleRemove'>Remove</button>")
  4. .withEventHandler("handleUpdate", person -> {
  5. person.setName(person.getName() + " Updated");
  6. grid.getDataProvider().refreshItem(person);
  7. }).withEventHandler("handleRemove", person -> {
  8. ListDataProvider<Person> dataProvider =
  9. (ListDataProvider<Person>) grid
  10. .getDataProvider();
  11. dataProvider.getItems().remove(person);
  12. dataProvider.refreshAll();
  13. })).setHeader("Actions");
  • When the server-side data used by the grid is edited, the grid’s DataProvider is refreshed by calling the refreshItem() method. This ensures the changes show up in the element.

  • When an item is removed, the refreshAll() method call ensures that all the data is updated.

  • You need to use Polymer notations for event handlers. on-click (with a dash) is Polymer syntax for the native onclick.

  • TemplateRenderer has a fluent API, so you can chain the commands, like TemplateRenderer.of().withProperty().withProperty().withEventHandler()…​

Using Component Renderers

You can use any component in the grid cells by providing a ComponentRenderer for a column.

To define how the component will be generated for each item, you need to pass a Function for the ComponentRenderer.

Example: Adding a column that contains a different icon, depending on the person’s gender.

Java

  1. Grid<Person> grid = new Grid<>();
  2. grid.setItems(people);
  3. grid.addColumn(new ComponentRenderer<>(person -> {
  4. if (person.getGender() == Gender.MALE) {
  5. return new Icon(VaadinIcon.MALE);
  6. } else {
  7. return new Icon(VaadinIcon.FEMALE);
  8. }
  9. })).setHeader("Gender");

It is also possible to provide a separate Supplier to create the component, and a Consumer to configure it for each item.

Example: Using ComponentRenderer with a Consumer.

Java

  1. SerializableBiConsumer<Div, Person> consumer =
  2. (div, person) -> div.setText(person.getName());
  3. grid.addColumn(
  4. new ComponentRenderer<>(Div::new, consumer))
  5. .setHeader("Name");

If the component is the same for every item, you only need to provide the Supplier.

Example: Using ComponentRenderer with a Supplier.

Java

  1. grid.addColumn(
  2. new ComponentRenderer<>(
  3. () -> new Icon(VaadinIcon.ARROW_LEFT)));

You can create complex content for the grid cells by using the component APIs.

Example: Using ComponentRenderer to create complex content that listens for events and wraps multiple components in layouts.

Java

  1. grid.addColumn(new ComponentRenderer<>(person -> {
  2. // text field for entering a new name for the person
  3. TextField name = new TextField("Name");
  4. name.setValue(person.getName());
  5. // button for saving the name to backend
  6. Button update = new Button("Update", event -> {
  7. person.setName(name.getValue());
  8. grid.getDataProvider().refreshItem(person);
  9. });
  10. // button that removes the item
  11. Button remove = new Button("Remove", event -> {
  12. ListDataProvider<Person> dataProvider =
  13. (ListDataProvider<Person>) grid
  14. .getDataProvider();
  15. dataProvider.getItems().remove(person);
  16. dataProvider.refreshAll();
  17. });
  18. // layouts for placing the text field on top
  19. // of the buttons
  20. HorizontalLayout buttons =
  21. new HorizontalLayout(update, remove);
  22. return new VerticalLayout(name, buttons);
  23. })).setHeader("Actions");
  • Editing grid items requires refreshing the grid’s DataProvider. The reasoning is the same as for Handling Events above.

See Data Providers for more.

Enabling Expanding Rows

The Grid supports expanding rows that reveal more detail about the items. The additional information is hidden, unless the user choses to reveal it, keeping the grid appearance clean and simple, while simultaneously allowing detailed explanations.

You can enable expanding rows using the setItemDetailsRenderer() method, which allows either a TemplateRenderer or a ComponentRenderer to define how the details are rendered.

Example: Using the setItemDetailsRenderer method with a ComponentRenderer.

Java

  1. grid.setItemDetailsRenderer(
  2. new ComponentRenderer<>(person -> {
  3. VerticalLayout layout = new VerticalLayout();
  4. layout.add(new Label("Address: " +
  5. person.getAddress().getStreet() + " " +
  6. person.getAddress().getNumber()));
  7. layout.add(new Label("Year of birth: " +
  8. person.getYearOfBirth()));
  9. return layout;
  10. }));

By default, the row’s detail opens by clicking the row. Clicking the row again, or clicking another row (to open its detail), automatically closes the first row’s detail. You can disable this behavior by calling the grid.setDetailsVisibleOnClick(false) method. You can show and hide item details programmatically using the setDetailsVisible() method, and test whether an item’s detail is visible using the isDetailsVisible() method.

Note
By default, items are selected by clicking them. If you want clicking to only show the item details without selection, you need to use the grid.setSelectionMode(SelectionMode.NONE) method.

Column Sorting

By default, this is how column sorting in the grid works:

  • The first click on the column header sorts the column.

  • The second click reverses the sort order.

  • The third click resets the column to its unsorted state.

If multi-sorting is enabled, the user can sort by multiple columns. The first click sorts the first column. Subsequent clicks on second and more sortable column headers, add secondary and more sort criteria.

Defining Column Sorting

The difference between in-memory and backend sorting is key to understanding the sorting mechanism:

  • In-memory sorting is sorting that is applied by the framework to items fetched from the backend, before returning them to the client.

  • Backend sorting is applied by providing a list of QuerySortOrder objects to your DataProvider, that typically passes the sort hints to the backend code, and in some cases all the way to database queries. See Data Providers for more.

The sorting mechanism is flexible. You can configure in-memory and backend sorting together or separately.

The sections that follow detail options you can use to set up sorting for your grid.

Using a Sort Property Name

By using a sort property, you can override or customise the property or multiple properties that are used for sorting the column. This option includes both in-memory and backend sorting. The property is defined at the time of column construction and uses a sort property name.

You can use the addColumn method to set a sort property to be used for backend sorting when the column is added to the grid.

Example: Using the addColumn method to set a column sort property.

Java

  1. grid.addColumn(Person::getAge, "age").setHeader("Age");
  • The Age column uses the values returned by the Person::getAge method to do in-memory sorting.

  • The column uses the age string to build a QuerySortOrder that is sent to the DataProvider to do the backend sorting.

You can also define multiple properties.

Example: Using the addColumn method to set multiple column sort properties.

Java

  1. grid.addColumn(person -> person.getName() + " " +
  2. person.getLastName(), "name", "lastName"
  3. ).setHeader("Name");
  • With multiple properties, the QuerySortOrder objects are created in the order they are declared.

You can also use use properties created for your TemplateRenderer.

Example: Using the addColumn method with TemplateRenderer to set column sort properties.

Java

  1. grid.addColumn(TemplateRenderer.<Person> of(
  2. "<div>[[item.name]]<br>" +
  3. "<small>[[item.email]]</small></div>")
  4. .withProperty("name", Person::getName)
  5. .withProperty("email", Person::getEmail),
  6. "name", "email")
  7. .setHeader("Person");
  • For in-memory sorting to work correctly, the values returned by the ValueProviders in the TemplateRenderer (Person::getName and Person::getEmail in this example) should implement Comparable.

  • The names of the sort properties must match the names of the properties in the template (set via withProperty).

Using a Comparator

This option is for in-memory sorting only, and uses a custom comparator.

If you need custom logic to compare items for sorting, or if your underlying data is not Comparable, you can set a Comparator for your column.

Example: Using the setComparator method to configure a comparator for a column.

Java

  1. grid.addColumn(Person::getName)
  2. .setComparator((person1, person2) ->
  3. person1.getName()
  4. .compareToIgnoreCase(person2.getName()))
  5. .setHeader("Name");

Setting Backend Sort Properties

This option is for backend sorting only, and uses a sort property name. It is similar to Using a Sort Property Name, but excludes in-memory sorting.

You can use the setSortProperty method to set strings describing backend properties to be used when sorting the column.

Example: Using the setSortProperty method to define sorting.

Java

  1. grid.addColumn(Person::getName)
  2. .setSortProperty("name", "email")
  3. .setHeader("Person");
  • Unlike using the sorting properties in the addColumn method directly, calling setSortProperty does not configure any in-memory sorting.

  • A SortOrderProvider is created automatically when the sort properties are set.

Setting a SortOrderProvider

This option is for backend sorting and uses a SortOrderProvider.

If you need fine-grained control over how QuerySortOrder objects are created and sent to the DataProvider, you can define a SortOrderProvider.

Example: Defining a SortOrderProvider for backend sorting.

Java

  1. grid.addColumn(Person::getName)
  2. .setSortOrderProvider(direction -> Arrays
  3. .asList(new QuerySortOrder("name", direction),
  4. new QuerySortOrder("email", direction))
  5. .stream())
  6. .setHeader("Person");

Enabling and Disabling Column Sorting

When a column is sortable, it displays the sorter element in the column header.

You can use the setSortable method to toggle the sorter element on an off.

Example: Using the setSortable method to disable sorting.

Java

  1. column.setSortable(false);

Setting a column as not sortable does not delete a Comparator, sort property, or SortOrderProvider that was previously set. You can toggle the sortable flag on and off, without reconfiguration.

To check if a column is currently sortable, you can use the isSortable method.

Example: Checking if a column is sortable.

Java

  1. column.isSortable();

Enabling Multi-sorting

To allow users to sort by more than one column at the same time, you can use the setMultiSort method to enable multi-sorting at the grid level.

Example: Using the setMultiSort method to enable multi-sorting.

Java

  1. grid.setMultiSort(true);

Receiving Sort Events

You can add a SortListener to the grid to receive general sort events. Every time sorting of the grid is changed, an event is fired. You can access the DataCommunicator to receive the sorting details.

Example: Using the addSortListener method to add a SortListener.

Java

  1. grid.addSortListener(event -> {
  2. String currentSortOrder = grid.getDataCommunicator()
  3. .getBackEndSorting().stream()
  4. .map(querySortOrder -> String.format(
  5. "{sort property: %s, direction: %s}",
  6. querySortOrder.getSorted(),
  7. querySortOrder.getDirection()))
  8. .collect(Collectors.joining(", "));
  9. System.out.println(String.format(
  10. "Current sort order: %s. User-clicked: %s.",
  11. currentSortOrder, event.isFromClient()));
  12. });

Styling the Grid

Styling the Grid component (or any Vaadin component) requires some Web Component and shadow-DOM knowledge. Styling depends on the components position in the DOM:

  • If the component is in the shadow DOM, you can apply styling within the component or using variables.

  • If the component is in the “normal” DOM (not in the shadow DOM), normal CSS styling applies.

In addition, the Grid supports the theme attribute that allows you to easily customize component styling.

Example: Celebrity grid used in styling examples below.

Java

  1. Grid<Celebrity> grid = new Grid<>();
  2. grid.setItems(Celebrity.getPeople());
  3. grid.addClassName("styled");
  4. grid.addColumn(new ComponentRenderer<>(person -> {
  5. TextField textField = new TextField();
  6. textField.setValue(person.getName());
  7. textField.addClassName("style-" +
  8. person.getGender());
  9. textField.addValueChangeListener(
  10. event -> person.setName(event.getValue()));
  11. return textField;
  12. })).setHeader("Name");
  13. grid.addColumn(new ComponentRenderer<>(person -> {
  14. DatePicker datePicker = new DatePicker();
  15. datePicker.setValue(person.getDob());
  16. datePicker.addValueChangeListener(event -> {
  17. person.setDob(event.getValue());
  18. });
  19. datePicker.addClassName("style-" +
  20. person.getGender());
  21. return datePicker;
  22. })).setHeader("DOB");
  23. grid.addColumn(new ComponentRenderer<>(person -> {
  24. Image image = new Image(person.getImgUrl(),
  25. person.getName());
  26. return image;
  27. })).setHeader("Image");

Styling with the Theme Property

The default Lumo theme includes different variations that you can use to style the grid. You can provide one or more variations.

Example: Using the addThemeVariants method to define theme variations for the grid.

Java

  1. grid.addThemeVariants(GridVariant.LUMO_NO_ROW_BORDERS,
  2. GridVariant.LUMO_NO_BORDER, GridVariant.LUMO_ROW_STRIPES);

Styling with CSS

You can use normal CSS styling for the content in the grid cells. While the Grid component itself is in the shadow DOM, the actual values (cell contents) are in slots and therefore in the light DOM.

Example: Setting the maximum size for images in the grid cells.

CSS

  1. vaadin-grid vaadin-grid-cell-content img {
  2. max-height: 4em;
  3. }
  • vaadin-grid-cell-content is in the light DOM, and the selector vaadin-grid vaadin-grid-cell-content points to all the grid’s cells.

You can also use a class to apply styles to a specific component instance.

Example: Applying rounded borders and centering images in a grid with “styled” class name.

CSS

  1. vaadin-grid.styled vaadin-grid-cell-content img {
  2. border-radius: 2em;
  3. margin-left: 50%;
  4. transform: translate(-50%);
  5. }

To learn how to customize the styles inside a component’s shadow DOM, see Styling Components.