Search code examples
javaselectvaadinvaadin6

How to set Vaadin 6 'Select' box select value


I'm using Vaadin 6 and need some help setting the value that gets selected once the user chooses an option from the dropdown box. Creating and adding some values to the Select box is easy:

Select sel = new Select();
sel.addItem("Value 1");
sel.addItem("Value 2");
sel.addItem("Value 3");

Getting the value is just as easy:

String selValue = (String) sel.getValue();

But the problem comes in where have a HashMap that I need to populate the Select:

HashMap<String, String> users = new HashMap<String, Sting>();
users.put("1", "John");
users.put("2", "Bob");
users.put("3", "Tom");

So in the select box I'd like to display the actual users name, but when it's selected I'd like the id to be passed. Is this possible? Or is it what you see-and-select is what you get?


Solution

  • You need to do:

    HashMap<String, String> users = new HashMap<String, String>();
    users.put("1", "John");
    users.put("2", "Bob");
    users.put("3", "Tom");
    
    Select select = new Select();
    for(Iterator<String> i = users.keySet().iterator(); i.hasNext();) {
        String key = i.next();
        select.addItem(key);
        select.setItemCaption(key, users.get(key));
    }
    
    String selValue = (String) select.getValue();
    

    So that adds the item, same as you were, but then sets what the user will see on the screen. Then when you get the value, it will return the id, not the displayed value.