How works selected value in NativeSelect with BeanItemContainer and FieldGr

Situation is this, I have object


class Type {
   private Integer id;
   private String title;

   // setter/getter
   // equals/hashcode
}

List of types is added to BeanItemContainer, and then as DataSource to NativeSelect (fType).


BeanItemContainer c = new BeanItemContainer<Type>(Type.class, typeList)
fType.setContainerDataSource(c);

fType is bound with FieldGroup, that has another object (Document) as DataSource, but when I pass document with data
NativeSelect does not select actual value from Document.


...
BeanItem<Document> item = new BeanItem<Document>(document);
item.addNestedProperty(Document.TYPE_PROPERTY_NAME);

FieldGroup fieldGrould = new FieldGroup();
fieldGroup.setItemDataSource(item);

NativeSelect fType = new NativeSelect("Type");
fType.setItemCaptionPropertyId("title");
fieldGroup.bind(fType, Document.TYPE_PROPERTY_NAME);
...

Why it doesn’t select value on binding, but only when I use fType.select() with instance of Type? Or BeanItemContainer and FieldGroup do not work together?

Not sure why you use addNestedProperty , but it depends on how Document looks

CASE 1. 
Document {
   private Type type; 
   // getter + setter  
}
OR CASE 2. 
Document {
   private Integer type; // reference to Type.id
   // getter + setter  
}

For case 1. if your type property is of type Type , the code below should work (bacause your itemId is the bean in the BeanItemContainer )


BeanItem<Document> item = new BeanItem<Document>(document);
FieldGroup fieldGrould = new FieldGroup();
fieldGroup.setItemDataSource(item);

NativeSelect fType = new NativeSelect("Type");
fType.setItemCaptionPropertyId("title");
fType.setContainerDataSource(new BeanItemContainer<Type>(Type.class, typeList)); // Set container before you bind.
fieldGroup.bind(fType, "type");  // Bind directly to type property in document...

For Case 2. if instead your type property is of type Integer ( ie referencing the primary key of Type ) , you have three approaches,

  1. Make derivative Container that uses the ID as ItemId instead of the bean itself ( extends AbstractBeanContainer<Integer,Type>and add an BeanIdResolver<Ineger,Type> resolver to the Container that resolves the ID for the Type.
  2. add the the items directly to the Native select using type.getId(), and set the Caption explicitly ( ie not using a BeanItemContainer )
for (Type t : typeList) {
   fType.addItem(t.getId());
   fType.setItemCaption(t.getId(), t.getTitle());
}
  1. (Have not tested ) , but you could add a Converter<PRESENTATION, MODEL> to the nativeSelect to convert your MODEL (Integer) to the presentation ( Type ) , and the default BeanItemContainer should still work.

Thank you Petrus Viljoen, the problem in place where I have set container for NativeSelect.