Search code examples
javacomboboxvaadinvaadin7

Vaadin set combo box value after it has been filled


My instance of the combo box is created globally, It gets filled with, lets say a list of companies while the value is an ID. After I load a File, I want to check that I have that value in the combo box and then select it programmatically.

class cComboBoxFun extends UI implements ClickListener
{
  ComboBox cb_company;
  List<cCustomer> ListCust;

  //default constructor and server conf not really relevant

  @Override
protected void init(VaadinRequest request) 
{
      //Lets assume the list has been filled already
      cb_company = new ComboBox("Company");

      for(cCustomer cust : ListCust)
      {
        cb_company.addItem(cust.mgetId);
        cb_company.setItemcaption(cust.mgetId, cust.mgetName);
      }


    }

    class cCustomer()
    {
      private String name;
      private String Id;

      public String GetName() 
      {
        return this.name
      }

       // Same for id

    }

I tried checking the value is there and setting it but nothing happens. I looked up but couldn't find an answer

if(cb_company.getItemCaption(value) != null)
    cb_company.set(value);

Solution

  • Assuming that your ComboBox uses single select mode, you can select a given item programatically with

    cb_company.select(value)
    

    where value points to cCustomer.Id. So the code may look as follows:

    cb_company = new ComboBox("Company");
    
    for(cCustomer cust : ListCust)
    {
        cb_company.addItem(cust.mgetId);
        cb_company.setItemcaption(cust.mgetId, cuts.mgetName);
    }
    
    //select the first item from the container
    cb_company.select(ListCust.get(0));