Search code examples
springcomboboxvaadin7

How to bind BeanItemContainer to Combobox


I have BeanItemContainer, which i load from database via jdbc:

BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, mybeanDao.findAll());

and this is how i attach it to combobox:

Combobox combo = new Combobox();
combobox.setContainerDataSource(myBeans);

So far, so good. I received what i want, but for now i have a problem - How do i get actual id that has been selected? This must be synchronized (id selected in combobox is actual entry in database).

I have no idea, how to solve this problem

Please help

P.S MyBean class

public class MyBean {

    private Long id;
    private String field1;

*** getters /setters ***
  and toString() {} method 
}

Solution

  • enter image description here Here is the code:

    @Theme("mytheme")
    public class MyUI extends UI {
    
    @Override
    protected void init(VaadinRequest vaadinRequest) {
        final VerticalLayout layout = new VerticalLayout();
        layout.setMargin(true);
        layout.setSpacing(true);
        setContent(layout);
    
        BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, getBeans());
    
        ComboBox combo = new ComboBox();
        combo.setContainerDataSource(myBeans);
        combo.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY);
        combo.setItemCaptionPropertyId("field");
    
        combo.addValueChangeListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(Property.ValueChangeEvent event) {
                MyBean bean = (MyBean) combo.getValue();
    
                Notification notif = new Notification("Selected Bean Id: "+bean.getId(), Notification.Type.TRAY_NOTIFICATION);
                notif.setPosition(Position.TOP_CENTER);
                notif.show(Page.getCurrent());
            }
        });
    
        layout.addComponent(combo);
    }
    
    @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
    @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
    public static class MyUIServlet extends VaadinServlet {
    }
    
    public class MyBean {
    
        private Long id;
        private String field;
    
        public MyBean(Long id, String field) {
            this.id = id;
            this.field = field;
        }
    
        public Long getId() {
            return id;
        }
    
        public String getField() {
            return field;
        }
    
    }
    
    public ArrayList<MyBean> getBeans() {
        ArrayList<MyBean> beans = new ArrayList<>();
    
        MyBean bean = new MyBean(1l, "Vikrant");
        beans.add(bean);
    
        bean = new MyBean(2l, "Rampal");
        beans.add(bean);
    
        bean = new MyBean(3l, "viky");
        beans.add(bean);
    
    
        return beans;
    }
    

    }