Method for generating item caption

Currently (AFAIK), the toString() method is used to display items in a component (e.g. Tree). This can be overridden by using setItemCaptionProperty().

But assume the following:
You want to display the first- and lastname of a person while still having a firstName and lastName field in your class. setItemCaptionProperty() doesn’t help here.

I did a workaround like this:

		for ( Object itemId : container.getItemIds() ) {
			BeanItem beanItem = ( BeanItem ) container.getItem( itemId );
			Person person = ( Person ) beanItem.getBean();
			component.setItemCaption( itemId, person.getFirstname() + " " + employee.getLastname() );
		}

But this still isn’t a good solution: When somewhere an item is added to the container, the toString() is used again.
Now you may say, I could simply override the toString(), but this isn’t an option as the Person class is generated by JAXB.

The solution would be that the components have a method that can be overridden, like this:


public String captionFor( itemId )

Another suggestion of Wolfie in IRC was giving something like an ItemCaptioner to the component:

ItemCaptioner captioner = new ItemCaptioner(){
  public String captionFor(Item item) {
    return "foo";
  }
}
component.setCaptioner( captioner )

I’d also prefer Wolfies solution, because this means you don’t have to extend such a component.

I created a ticket:
http://dev.vaadin.com/ticket/3238

How about adding a property to the container that contains the caption in the format you want it?

IndexexContainer container = new IndexedContainer();
container.addContainerproperty("userFriendlyName", String.class, "");
for(Person person : getPersons()){
  Item item = container.addItem(person);
  item.getItemProperty("userFriendlyName").setValue(person.getFirstName() + " " + person.getLastName());
}
Select select = new Select();
select.setContainerDataSource(container);
select.setItemCaptionPropertyId("userFriendlyName");

or did I misunderstand what you wanted to do here?

Your solution does quite the same as my current one. If I add a new Item i had to manually set the caption again. This is not good for maintaining.

I already submitted a patch for my and Wolfies’ desired solution :slight_smile: