具有不同属性以显示和绑定的 Vaadin 组合框

Vaadin combobox with different properties to display and bind

我有两个域名类

public class A {
  private String nick;
  private String bId;

  // getters & setters
}

public class B {
  private String id;
  private String name;

  // a lot of other fields
  // getter and setters
}

想法是A不保存完整的b,只保存它的id。

现在喜欢在Vaadin(7.6.7)中新建一个表单A。可用对象的数量有限 B,所以我喜欢有一个组合框,用户可以在其中 select 一个 B.

由于Bid是一个非用户友好的字段,我喜欢有一个组合框,绑定到属性 bId A 对象并以 B.

的 属性 name 呈现自身

我不知道这段代码应该是什么样子。

FormLayout layout = new FormLayout();
BeanFieldGroup<A> dataBinder = new BeanFieldGroup(A.class);
Field<?> nickField = dataBinder.buildAndBind("nick");
layout.addComponent(nickField);

Combobox bBox = new Combobox("B");
List<B> allBs = ... // get all Bs;
allBs.stream().forEach(bBox::addItem);
dataBinder.bind(bBox, "bId");
// this does not work really

我知道问题是我将类型为 B 的组合框绑定到类型为 String 的字段,但我该怎么做才能显示所有 [=15] =]s 与 Combobox 中的名称,但是当 commit 发生时,它使用 Bid ?

我建议使用 ComboBox.setItemCaption(..):

明确设置项目标题
for (final B b : allBs) {
    bBox.setItemCaption(b.getId(), b.getName());
}

然后您将 ComboBox'属性 绑定到 A 的 bId,并将 ComboBox' 容器数据源绑定到您自己设置的 B ID 列表。

bBox.setContainerDataSource(new BeanItemContainer<>(
            String.class, allBIds));

或手动设置组合框项目:

for (final B b : allBs) {
    bBox.addItem(b.getId());
}

Here 是组合框的示例,可能对您也有帮助。