JPA relationship JPAContainer with ComboBox?

半城伤御伤魂 提交于 2019-12-02 10:12:58

A straight forward solution:

BeanItemContainer<State> container = new BeanItemContainer<State>(State.class);

final BeanFieldGroup<State> binder = new BeanFieldGroup<State>(State.class);
binder.setFieldFactory(new DefaultFieldGroupFieldFactory() {

    @SuppressWarnings("unchecked")
    @Override
    public <T extends Field> T createField(Class<?> type, Class<T> fieldType) {

        if (type.isAssignableFrom(Governor.class) && fieldType.isAssignableFrom(ComboBox.class)) {
            return (T) new ComboBox(); // we create a ComboBox for the Governor property
        }

        return super.createField(type, fieldType);
    }

});

final State bean = new State();

Field<?> field = null;
binder.setItemDataSource(bean);

binder.buildAndBind("State", "state");
field = binder.buildAndBind("Governor", "governor", ComboBox.class);

ComboBox cmbx = (ComboBox) field;

// We define a container data source for your Governors.
// I've taken the BeanItemContainer
cmbx.setContainerDataSource(new BeanItemContainer<Governor>(Governor.class));

// If you want to use a JPAContainer you need to translate entities to identifiers and visa versa
// cmbx.setContainerDataSource(dsGovernor);
// cmbx.setConverter(new SingleSelectConverter<Governor>(cmbx));
cmbx.setItemCaptionPropertyId("governor");

// we create two dummy Governors
Governor governorA = new Governor();
governorA.setGovernor("A");
Governor governorB = new Governor();
governorB.setGovernor("B");

// ... and add them to the container
cmbx.getContainerDataSource().addItem(governorA);
cmbx.getContainerDataSource().addItem(governorB);

// when the binder is committed the value of the ComboBox ( getValue() )is mapped to our state bean.
Roland Krüger

This question is related to another question on Stackoverflow: Vaadin 7.0.1 Combobox with JPAContainer and FieldGroup.

I wrote a blog post about this topic which explains how FieldGroups work internally and how you can make them work for this particular use case: Select Nested JavaBeans With a Vaadin FieldGroup. This post will also explain why a ConversionException is thrown in your example.

Of course you could switch to using a BeanItemContainer, but by using a simple Converter implementation you can use any Container implementation as data source for your ComboBox. See the blog post for details.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!