1

I want to show data in vaadin's grid, but I want to create columns dynamically for each value from customAttributes list. My data model more or less look like this

Item
    name: String
    localization: Localization
    visible: Boolean
    customAttributes: List<CustomAttribute>

CustomAttribute
    name: String
    value: String

Each Item has the same set of attribute types, only the values are different. User can manually defined new attribute types.

How can I create this grid? Currently I do it in this way:

grid.setColumns("name", "visible");
grid.addColumn(v -> v.getLocalization().getName()).setHeader("Localization");

But I have no idea for dynamic creating columns for each custom attribute.

foxbuur
  • 169
  • 1
  • 9
  • By custom atttibute, do you mean adding a column to the grid? Does a custom attribute apply to all the rows in the grid? And how many custom attributes do you expect? Your own code shows `grid.addColumn`, so I’m having a difficult time understanding what is confusing you or limiting you. – Basil Bourque Apr 26 '22 at 23:31
  • You should be able to loop over your list of custom attributes and call grid.addColumn for each . – Marcus Hellberg Apr 26 '22 at 23:43

1 Answers1

1

Like it was already written in the comments, you can loop over the attribute names assuming your have a list (or set) of them. One small gotcha is that you need to do that in a way that ensures values inside the callback are effectively final.

attributeNames.forEach(name -> {
  grid.addColumn(item -> item.getCustomAttributes().get(name))
    .setHeader(name);
});

If you don't directly know the attribute names but you're loading all items into memory instead of lazy loading them, then you can find the unique names by iterating over all items:

items.stream().flatMap(item -> item.getCustomAttributes().keySet().stream())
  .distinct().forEach(<same loop as in the previous example>);
Leif Åstrand
  • 7,820
  • 13
  • 19