Showing a List of Data with Data Providers

Many applications present the user with a list of items from which they can select one or more items to work on. Example lists include inventory records to survey, messages requiring a response, or blog drafts to edit or publish.

A listing component is a component that:

  • Displays one or several properties from a list of items,

  • Allows the user to inspect the data and mark items as selected, and

  • Optionally, allows the user to edit items directly in the component.

There are a number of officially-supported listing components, such as ListBox and ComboBox. Each component has its own API to configure exactly how the data is represented and manipulated.

All list components have a setItems method to define which items display. They also have the DataProvider interface for more fine-grained control of the displayed data.

Changing How Items Display

By default, most components use the toString() method to display items. If this is not suitable, you can change the behavior by configuring the component. Components are configured with one or more callbacks that define how to display the items.

Example: A ComboBox component that lists status items and uses the Status.getLabel() method to represent each status. There is also a Grid with two columns, Name and Year of birth. .

Java

  1. ComboBox<Status> comboBox = new ComboBox<>();
  2. comboBox.setItemLabelGenerator(Status::getLabel);
  3. Grid<Person> grid = new Grid<>();
  4. grid.addColumn(Person::getName).setHeader("Name");
  5. grid.addColumn(Person::getYearOfBirth)
  6. .setHeader("Year of birth");

Displaying In-memory Data

The easiest way to pass data to listing components is to use the setItems method. It accepts a collection, an array, or a stream of items.

Example: Passing data values to setItems.

Java

  1. // Sets items as a collection
  2. comboBox.setItems(EnumSet.allOf(Status.class));
  3. // Sets items using varargs
  4. grid.setItems(
  5. new Person("George Washington", 1732),
  6. new Person("John Adams", 1735),
  7. new Person("Thomas Jefferson", 1743),
  8. new Person("James Madison", 1751)
  9. );

Sorting In-memory Data

Listing components that allow the user to control the item-display order, such as Grid, are automatically also capable of sorting data by any property, provided the property type implements Comparable.

You can also define a custom Comparator if you need to customize the way a specific column is sorted. The comparator can be based on either the item instances or on the displayed property values.

Example: Defining a custom comparator.

Java

  1. grid.addColumn(Person::getName)
  2. .setHeader("Name")
  3. // Override default natural sorting
  4. .setComparator(Comparator.comparing(person ->
  5. person.getName().toLowerCase()));
Note
This kind of sorting is only supported for in-memory data. See Sorting Lazy-loaded Data for how to sort data loaded from a backend service.

Lazy Loading Data from a Backend Service

When fetching data from a backend service, it is often more efficient to only load the items that currently display. For example, when loading all available data uses excessive memory or slows down page load.

Note
Regardless of how you make the items available to the listing component on the server, components like Grid will always take care of only sending the currently needed items to the browser.

Assume you have a prebuilt backend service that fetches items from a database or a REST service.

Example: Prebuilt PersonService.

Java

  1. public interface PersonService {
  2. List<Person> fetchPersons(int offset, int limit);
  3. int getPersonCount();
  4. }

To use this service with a listing component, you can create a data provider that defines two callbacks using the fromCallbacks method.

Example: Data provider with callbacks that fetch specified items and the number of items available.

  • The first callback loads specific items.

  • The second callback finds out how many items there are in total in the datasource matching with current filters. Since there is no filtering employed in this example, the returned value is equal to the total amount of items in the datasource.

  • Information about the items to fetch is made available in a Query object that is passed to both callbacks

  • Information about the items to fetch includes offset, limit.

Java

  1. DataProvider<Person, Void> dataProvider =
  2. DataProvider.fromCallbacks(
  3. // First callback fetches items based on a query
  4. query -> {
  5. // The index of the first item to load
  6. int offset = query.getOffset();
  7. // The number of items to load
  8. int limit = query.getLimit();
  9. List<Person> persons = getPersonService()
  10. .fetchPersons(offset, limit);
  11. return persons.stream();
  12. },
  13. // Second callback fetches the total number of items currently in the Grid.
  14. // The grid can then use it to properly adjust the scrollbars.
  15. query -> getPersonService().getPersonCount());
  16. );
  17. Grid<Person> grid = new Grid<>();
  18. grid.setDataProvider(dataProvider);
  19. // Columns are configured in the same way as before
  • The results of the first and second callbacks must go hand in hand. If you do filtering for the items in the first query, the second callback reporting the total amount of items must apply the same filter (without limit/offset). Since this example doesn’t impose any filtering, the returned number of items is equal to the total items in the datasource.

  • The second DataProvider type parameter defines how the provider can be filtered. In the example, the filter type is Void, meaning filtering in not supported. See Filtering Lazy-loaded Data below for more.

Note
The number of items that need to be fetched, query.getLimit(), is set by the component that uses the DataProvider. For example, in Grid component the default number is 50. This number can be changed via its constructor, like Grid<Person> grid = new Grid<>(20);, or via its setPageSize method, like grid.setPageSize(20);.

Sorting Lazy-loaded Data

It is not practical to order items based on a Comparator when the items are loaded on demand, because this requires all items to be loaded and inspected.

Every backend has a defined way of ordering fetched items. Generally, ordering is based on a list of property names and whether it should be ascending or descending.

Example: PersonService interface with descending ordering based on a property name.

Java

  1. public interface PersonService {
  2. List<Person> fetchPersons(
  3. int offset,
  4. int limit,
  5. List<PersonSort> sortOrders);
  6. int getPersonCount();
  7. PersonSort createSort(
  8. String propertyName,
  9. boolean descending);
  10. }

When using this service interface, you can enhance the data source by converting the provided sorting options into a format expected by the service.

Sorting options set in the component are available using the query.getSortOrders() method.

Example: Using the query.getSortOrders() method in a component.

Java

  1. DataProvider<Person, Void> dataProvider =
  2. DataProvider.fromCallbacks(query -> {
  3. List<PersonSort> sortOrders = new ArrayList<>();
  4. for(SortOrder<String> queryOrder :
  5. query.getSortOrders()) {
  6. PersonSort sort = getPersonService()
  7. .createSort(
  8. // The name of the sorted property
  9. queryOrder.getSorted(),
  10. // The sort direction for this property
  11. queryOrder.getDirection() ==
  12. SortDirection.DESCENDING);
  13. sortOrders.add(sort);
  14. }
  15. return getPersonService().fetchPersons(
  16. query.getOffset(),
  17. query.getLimit(),
  18. sortOrders
  19. ).stream();
  20. },
  21. // The number of persons is the same
  22. // regardless of ordering
  23. query -> getPersonService().getPersonCount()
  24. );

It is also necessary to configure the Grid to know which property name to include in the query when the user wants to sort by a specific column. When a data source does lazy loading, Grid and similar listing components, only allow the user to sort by columns if a sort property name is provided.

Example: Configuring a property name in Grid to be used for sort queries.

Java

  1. Grid<Person> grid = new Grid<>();
  2. grid.setDataProvider(dataProvider);
  3. // Will be sortable by the user
  4. // When sorting by this column, the query
  5. // will have a SortOrder
  6. // where getSorted() returns "name"
  7. grid.addColumn(Person::getName)
  8. .setHeader("Name")
  9. .setSortProperty("name");
  10. // Will not be sortable since no sorting info is given
  11. grid.addColumn(Person::getYearOfBirth)
  12. .setHeader("Year of birth");

In some cases, providing a single property name is not enough. For example, if the backend sorts by multiple properties for one column in the UI, or if the backend sort order needs to be inverted when compared to the sort order defined by the user. In these cases, you need to define a callback that generates suitable SortOrder values for the given column.

Example: Generating a SortOrder by last name and then first name.

Java

  1. grid.addColumn(person ->
  2. person.getName() + " " + person.getLastName())
  3. .setHeader("Name")
  4. .setSortOrderProvider(
  5. // Sort according to last name, then first name
  6. direction -> Stream.of(
  7. new QuerySortOrder("lastName", direction),
  8. new QuerySortOrder("firstName", direction)));

Filtering Lazy-loaded Data

Different backends support filtering in different ways: some offer no filtering support, some allow filtering by a single value (of a specific type), and some support complex filtering options.

The following examples use the ComboBox component to demonstrate filtering in various scenarios.

Filtering by a Single String

A DataProvider<Person, String> accepts a single string to filter by in the query. How the data provider uses this value depends on the implementation. It could, for example, look for all Persons with a name beginning with the provided string.

Listing components that allow the user to control how displayed data is filtered, all use a specific filter type. For ComboBox, the filter is the string the user enters in the search field. This means that you can only use ComboBox with a data provider with a String filtering type.

Example: DepartmentService backend service.

Java

  1. public interface DepartmentService {
  2. List<Department> fetch(int offset, int limit,
  3. String filterText);
  4. int getCount(String filterText);
  5. }
  • Note, getCount method takes into account the filtering criteria when returning the total amount of available items.

Example: DataProvider that uses the DepartmentService interface service methods to fill a ComboBox component with data.

Java

  1. DataProvider<Department, String>
  2. createDepartmentDataProvider(DepartmentService service)
  3. {
  4. return DataProvider.fromFilteringCallbacks(query -> {
  5. // getFilter returns Optional<String>
  6. String filter = query.getFilter().orElse(null);
  7. return service.fetch(query.getOffset(),
  8. query.getLimit(), filter).stream();
  9. }, query -> {
  10. String filter = query.getFilter().orElse(null);
  11. return service.getCount(filter);
  12. });
  13. }

Example: Using the DataProvider.

Java

  1. DataProvider<Department, String> dataProvider =
  2. createDepartmentDataProvider(service);
  3. ComboBox<Department> departmentComboBox =
  4. new ComboBox<>();
  5. departmentComboBox.setDataProvider(dataProvider);

Filtering Based on Another Component

In this scenario, filtering is based on the value of a different component than the combo box component you are working on. For example, you are defining a combo box to select an employee that is filtered by the value of a combo box for selecting a department. The employee combo box should also allow filtering by text entered by the user.

Example: Backend EmployeeService.

Java

  1. public interface EmployeeService {
  2. List<Employee> fetch(int offset, int limit,
  3. EmployeeFilter filter);
  4. int getCount(EmployeeFilter filter);
  5. }
  6. public class EmployeeFilter {
  7. private String filterText;
  8. private Department department;
  9. public EmployeeFilter(String filterText,
  10. Department department) {
  11. this.filterText = filterText;
  12. this.department = department;
  13. }
  14. public String getFilterText() {
  15. return filterText;
  16. }
  17. public void setFilterText(String filterText) {
  18. this.filterText = filterText;
  19. }
  20. public Department getDepartment() {
  21. return department;
  22. }
  23. public void setDepartment(Department department) {
  24. this.department = department;
  25. }
  26. }

Because there are two different types of filters - one for the input text and one for the selected department - you can no longer use DataProvider<Employee, String> directly. To overcome this, you can create a data provider wrapper that allows you to set the filter value to include in the query programmatically.

Example: Using the withConfigurableFilter method to create a ConfigurableFilterDataProvider<Employee, String, Department>.

Java

  1. ConfigurableFilterDataProvider<Employee, String,
  2. Department> getDataProvider(EmployeeService service) {
  3. DataProvider<Employee, EmployeeFilter> dataProvider =
  4. DataProvider.fromFilteringCallbacks(query -> {
  5. // getFilter returns Optional<String>
  6. EmployeeFilter filter = query.getFilter()
  7. .orElse(null);
  8. return service.fetch(query.getOffset(),
  9. query.getLimit(), filter).stream();
  10. }, query -> {
  11. EmployeeFilter filter = query.getFilter()
  12. .orElse(null);
  13. return service.getCount(filter);
  14. });
  15. ConfigurableFilterDataProvider<Employee, String,
  16. Department> configurableFilterDataProvider =
  17. dataProvider.withConfigurableFilter(
  18. (String filterText, Department department) ->
  19. new EmployeeFilter(filterText, department));
  20. return configurableFilterDataProvider;
  21. }

Example: Using the DataProvider:

Java

  1. ConfigurableFilterDataProvider<Employee, String,
  2. Department> employeeDataProvider =
  3. getDataProvider(service);
  4. ComboBox<Employee> employeeComboBox = new ComboBox<>();
  5. employeeComboBox.setDataProvider(employeeDataProvider);

Example: Manually setting the department when it changes by calling the setFilter method.

Java

  1. departmentComboBox.addValueChangeListener(event -> {
  2. employeeDataProvider.setFilter(event.getValue());
  3. employeeDataProvider.refreshAll();
  4. });

Flexible Filtering Using a Predicate Parameter

You can a predicate parameter in your service methods to implement flexible filtering.

Example: Backend PersonService.

Java

  1. public interface PersonService {
  2. List<Person> fetch(int offset, int limit,
  3. Optional<Predicate<Person>> predicate);
  4. int getCount(Optional<Predicate<Person>> predicate);
  5. }

While it is still possible to use the fromFilteringCallbacks method to create a DataProvider<Person, String> directly, the example below is a far cleaner coding solution.

Example: Creating a DataProvider<Person, Predicate<Employee>> and converting it into a DataProvider<Person, String> using the withConvertedFilter method.

Java

  1. DataProvider<Person, String> getDataProvider(
  2. PersonService service) {
  3. DataProvider<Person, Predicate<Person>>
  4. predicateDataProvider =
  5. DataProvider.fromFilteringCallbacks(
  6. query -> service.fetch(query.getOffset(),
  7. query.getLimit(),
  8. query.getFilter()).stream(),
  9. query -> service.getCount(query.getFilter()));
  10. DataProvider<Person, String> dataProvider =
  11. predicateDataProvider.withConvertedFilter(
  12. text -> (person -> person.getName()
  13. .startsWith(text)));
  14. return dataProvider;
  15. }
  • The withConvertedFilter method allows you to use a data provider that filters by another type.

  • The example filters a series of people by name. When users input text, it is not used directly to select data items from the existing objects. A lambda produces a predicate (another lambda) that filters the people by name.

Example: Using the DataProvider.

Java

  1. DataProvider<Person, String> dataProvider =
  2. getDataProvider(service);
  3. ComboBox<Person> comboBox = new ComboBox<>();
  4. comboBox.setDataProvider(dataProvider);

Filtering in the Grid Component

You can use the withConfigurableFilter method on a data provider to create a data provider wrapper that allows you to configure the filter that is passed through the query.

All components that use the same data provider refresh their data when a new filter is set.

Example: Using the withConfigurableFilter method to create a data provider wrapper.

Java

  1. DataProvider<Employee, String> employeeProvider =
  2. getEmployeeProvider();
  3. ConfigurableFilterDataProvider<Employee, Void, String>
  4. wrapper = employeeProvider.withConfigurableFilter();
  5. Grid<Employee> grid = new Grid<>();
  6. grid.setDataProvider(wrapper);
  7. grid.addColumn(Employee::getName).setHeader("Name");
  8. searchField.addValueChangeListener(event -> {
  9. String filter = event.getValue();
  10. if (filter.trim().isEmpty()) {
  11. // null disables filtering
  12. filter = null;
  13. }
  14. wrapper.setFilter(filter);
  15. });
  • The filter type of the wrapper instance is Void. This means that the data provider does not support further filtering through the query. It is therefore not possible to use this data provider with a combo box.

Refreshing Data from a Backend Service

DataProvider has two methods, refreshAll and refreshItems, that you can use to ensure that backend changes reflect in all parts of you application.

Whether refreshing is required depends on your implementation and environment. Spring Data, for example, gives new instances with every request, and changes to the repository make old instances of the same object “stale”. In cases similar to this, you should inform interested components by calling dataProvider.refreshItem(newInstance). This works out of the box, if your beans have equals and hashCode implementations that check if the objects represent the same data. Since this is not always the case, when using CallbackDataProvider you can give it a ValueProvider that will provide a stable ID for the data objects. This is usually a method reference, for example Person::getId.

Example: PersonService interface with an update method that returns a new instance of the item. Other functionality is omitted.

Java

  1. public interface PersonService {
  2. Person save(Person person);
  3. }

Example: Data provider to update a person’s name and save it to the backend.

Java

  1. DataProvider<Person, String> allPersonsWithId =
  2. new CallbackDataProvider<>(
  3. fetchCallback, sizeCallback, Person::getId);
  4. Grid<Person> persons = new Grid<>();
  5. persons.setDataProvider(allPersonsWithId);
  6. persons.addColumn(Person::getName).setHeader("Name");
  7. Button modifyPersonButton = new Button("", event -> {
  8. Person personToChange = service.fetchById(128);
  9. personToChange.setName("Changed person");
  10. Person newInstance = service.save(personToChange);
  11. allPersonsWithId.refreshItem(newInstance);
  12. });

Using a ListDataProvider for Advanced In-memory Data Handling

As an alternative to assigning the items in a collection directly, you can create a ListDataProvider that contains the items a component should use.

Multiple components can share a single list data provider to display the same data. You can also configure the instance to filter out some items or display items in a specific order.

For components like Grid that can be separately configured to sort data in a specific way, sorting configured in the data provider is only used as a fallback. The fallback is used if no sorting is defined in the component, or if the order between items is considered equal by the component’s sorting definition. Components update automatically when you change sorting in the data provider.

Example: Defining differing sort orders in the ListDataProvider and components.

Java

  1. ListDataProvider<Person> dataProvider =
  2. DataProvider.ofCollection(persons);
  3. dataProvider.setSortOrder(Person::getName,
  4. SortDirection.ASCENDING);
  5. Grid<Person> grid = new Grid<>(Person.class);
  6. // The grid shows the persons sorted by name
  7. grid.setDataProvider(dataProvider);
  8. // Makes the combo box show persons in descending order
  9. button.addClickListener(event -> {
  10. dataProvider.setSortOrder(Person::getName,
  11. SortDirection.DESCENDING);
  12. });

Filtering In-memory Data

You can configure the list data provider to always apply a specific filter to limit which items display, or to filter by data that is not included in the displayed item caption.

Example: Defining a ListDataProvider with a filter.

Java

  1. ListDataProvider<Person> dataProvider =
  2. DataProvider.ofCollection(persons);
  3. ComboBox<Person> comboBox = new ComboBox<>();
  4. comboBox.setDataProvider(dataProvider);
  5. departmentSelect.addValueChangeListener(event -> {
  6. Department selectedDepartment = event.getValue();
  7. if (selectedDepartment != null) {
  8. dataProvider.setFilterByValue(
  9. Person::getDepartment,
  10. selectedDepartment);
  11. } else {
  12. dataProvider.clearFilters();
  13. }
  14. });
  • The selected department in the departmentSelect component is used to dynamically change the persons displayed in the combo box.

  • In addition to setFilterByValue, it is also possible to set a filter based on a predicate that tests each item or the value of some specific property in the item.

  • Multiple filters can be stacked using addFilter methods instead of setFilter.

Notifying the Data Provider About Item Changes

The listing component does not automatically know about changes to the list of items or the individual items. For changes to reflect in the component, you need to notify the list data provider when items are changed, added or removed.

DataProvider has two methods for this purpose, refreshAll and refreshItems.

Example: Using the refreshAll and refreshItems methods to update the data provider.

Java

  1. ListDataProvider<Person> dataProvider =
  2. new ListDataProvider<>(persons);
  3. Button addPersonButton = new Button("Add person",
  4. clickEvent -> {
  5. persons.add(new Person("James Monroe",
  6. 1758));
  7. dataProvider.refreshAll();
  8. });
  9. Button modifyPersonButton = new Button("Modify person",
  10. clickEvent -> {
  11. Person personToChange = persons.get(0);
  12. personToChange.setName("Changed person");
  13. dataProvider.refreshItem(personToChange);
  14. });