user2486322
user2486322

Reputation: 867

Vaadin Grid setColumn() - set member object's field as a column

Assume I have the below scenario:

There are two entities:

public class Address {

  private City city;
  private String street;

  public String getStreet() {
    return street;
  }

  public void setStreet(String street) {
    this.street = street;
  }

  public City getCity() {
    return city;
  }

  public void setCity(City city) {
    this.city = city;
  }
}

And

public class City {

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

I want to show street and city name on a grid component using BeanItemContainer, how should I specify the column names?

P tried using "street" and "city.name", but it throws an exception.

java.lang.IllegalStateException: Found at least one column in Grid that does not exist in the given container: city.name with the header "Name". Call removeAllColumns() before setContainerDataSource() if you want to reconfigure the columns based on the new container.

Upvotes: 1

Views: 1591

Answers (1)

Morfic
Morfic

Reputation: 15518

You did not show the code related to the grid, however you can see below at least 2 ways of doing it (please note that for convenience I've created some constructors for your objects):

Code:

public class MyUi extends UI {
    @Override
    protected void init(VaadinRequest request) {
        // basic stuff
        Layout content = new VerticalLayout();
        content.setSizeFull();
        setContent(content);

        // container & grid
        BeanItemContainer<Address> container = new BeanItemContainer<>(Address.class);
        Grid grid = new Grid(container);

        // 1) either manually add nested properties and hide the actual inner bean
        container.addNestedContainerProperty("city.name");
        grid.getColumn("city.name").setHeaderCaption("City");
        grid.setColumns("street", "city.name"); // hide bean column

        // 2) or make the container create nested properties for your inner beans
        container.addNestedContainerBean("city");
        grid.getColumn("city.name").setHeaderCaption("City");

        // create some dummy data to populate the grid
        City city = new City("There");
        Address address = new Address(city, "Here");
        container.addItem(address);
        content.addComponent(grid);
    }
}

Result:

Sample

Upvotes: 2

Related Questions