Vaadin ComboBox with values and IDs

blueFast picture blueFast · May 30, 2012 · Viewed 21.8k times · Source

I have defined a ComboBox which allows the user to select a contact from his contact list. The ComboBox is showing the contact name, but that can not really be used to map to the real contact: the contact ID is needed. My problem is that I do not know how to populate the Vaadin ComboBox with linked values and IDs, but only showing the values.

// Add all organization contacts to the drop-down
for (Contact contact : organizationContacts) {
    contactName = contact.getName();
    contactId   = contact.getId();
    _logger.debug("Adding contactName=" + contactName + " contactId=" + contactId + " to person with id=" + personId);
    contactNameCombo.addItem(contactName);
}

// Add the contact of this person, and select it in the drop-down
contactName = person.getContact().getName();
contactId   = person.getContact().getId();
contactNameCombo.addItem(contactName);
contactNameCombo.setValue(contactName);

As you can see in the code above, I am adding the contactName to the ComboBox, but I do not know how to add also the contactId so that I can know later, from the selected entry, which ID must be used to update the database.

Answer

Charles Anthony picture Charles Anthony · May 30, 2012

There are several ways to approach this : the most flexible here is to configure the combobox to use a named property as a caption. See Book Of Vaadin on Selecting Items for more details.

// Set the caption mode to read the caption directly
// from the 'name' property of the item
contactNameCombo.setItemCaptionMode(Select.ITEM_CAPTION_MODE_PROPERTY);
contactNameCombo.setItemCaptionPropertyId("name");

// Add all organization contacts to the drop-down
for (Contact contact : organizationContacts) {
    contactName = contact.getName();
    contactId   = contact.getId();
    _logger.debug("Adding contactName=" + contactName + " contactId=" + contactId + " to person with id=" + personId);

    // Note : the itemId of the item is the contactId
    Item item = contactNameCombo.addItem(contactId);
    item.getProperty("name").setValue(contactName)
}
// Add the contact of this person, and select it in the drop-down
contactName = person.getContact().getName();
contactId   = person.getContact().getId();
Item item = contactNameCombo.addItem(contactId);
item.getProperty("name").setValue(contactName)

// Using the itemId (which = contactId) to select the given contact
contactNameCombo.setValue(contactId);