Skizzo
Skizzo

Reputation: 2983

How to add and modify bean in BeanItemContainer

I'm developing a Vaadin application. Now, I have a trouble with a BeanItemContainer. I have a few items inside my container.

private void populateTable() {
  tableContainer.removeAllItems();
  for(MyBean  myBean : beans){
  tableContainer.addItem(myBean);
  }
}

When I select the item in the table, I bind the item selected with the binder and I fill the form automatically

table.addItemClickListener(new ItemClickListener() {
  public void itemClick(ItemClickEvent event) {
    myBean = ((BeanItem<MyBean>) event.getItem()).getBean();                
    //BeanFieldGroup<MyBean>
    binder.setItemDataSource(myBean);
  }
}); 

private Component makeForm() {      
  formLayout = new FormLayout();
  binder.bind(comboBoxModPag,"modPagamento");
  binder.bind(fieldInizioVal,  "id.dInizioVal");
  formLayout.addComponent(comboBoxModPag);
  formLayout.addComponent(fieldInizioVal);
  formLayout.addComponent(binder.buildAndBind(getI18NMessage("dValidoAl"), "dValidoAl", DateField.class));
  return formLayout;        
}

Now, I have to manage the user interactions in a different way. For example, if the user modify the value inside the combobox, I have to add a new Bean in the container, while if the users modify the value of the field fieldInizioVal I have to update the current Bean.

insertOrUpdateButton.addClickListener(new ClickListener() {
  @Override
  public void buttonClick(ClickEvent event) {
    tableContainer.addItem(myBean));
  }
});

But, when add a new Item, the container adds the new item correctly but modify also the old item selected.

How can I do?

Upvotes: 1

Views: 4034

Answers (1)

Skizzo
Skizzo

Reputation: 2983

I solved in this way

comboBoxModPag.addValueChangeListener(new ValueChangeListener() {

public void valueChange(ValueChangeEvent event) {
    MyBean oldValue = (MyBean) comboBoxModPag.getOldValue();
    MyBean newValue = (MyBean) comboBoxModPag.getValue();

        if( oldValue!=null &&  newValue!=null && !oldValue.equals(newValue) ){
            insertMode = true;
        }
        else{
            insertMode = false;
        }

    }

}
});

protected void saveOrUpdateModPagContrattoSito() {
if(insertMode){
    MyBean newMyBean = new MyBean(myBean);

    //Do somethings to restore myBean statuse 
    //....
    //....
    tableContainer.addBean(newMyBean);
}
else{
    tableContainer.addBean(myBean);
}
table.refreshRowCache();
}

But I don't know if this is the correct way.

Upvotes: 1

Related Questions