0

Is it possible in vaadin 12 to have comboboxes such that it displays a user-friendly value but behind the scenes it stores a hidden code? I found this example from 5 years ago but it doesn't apply to Vaadin 12 comboboxes: https://vaadin.com/forum/thread/7821327/combo-box-hidden-values

(If there's a good, reasonably clean way to do it, please point me in the right direction! I would think this is a common sought-after feature)

Jonathan Sylvester
  • 1,275
  • 10
  • 23

2 Answers2

3

Items are assigned to ComboBox either directly using setItems or indirectly through setDataProvider.

The item itself is not sent to the browser and shown in the dropdown. Instead, for each item ComboBox generates a string label that is shown in the UI and an internal id that is used on the server for mapping back to the original item instance when the user makes a selection.

The generated id is internal to ComboBox and has no external meaning. In particular, it's not based on any value in the item itself such as the item's primary key in the application's database.

The label is by default based on doing toString() for each item. You can customize how the label is created by assigning an item label generator callback that receives an item instance and returns the label string to use for that item.

If you for example have a combo box for selecting persons, then you could configure it in e.g. this way:

ComboBox<Person> personSelector = new ComboBox<>();
personSelector.setItems(allPersons);
personSelector.setItemLabelGenerator(person ->
  person.getFirstName() + " " + person.getLastName());
Leif Åstrand
  • 7,820
  • 13
  • 19
  • Not only did this work, it was better than my original idea of using hidden keys etc and then having to write logic to dereference these hidden keys into the original java objects...this is a nice feature of Vaadin. – Jonathan Sylvester Feb 04 '19 at 17:41
2

If I understand you correctly, there is built-in feature in ComboBox for this, the method is called setItemLabelGenerator(..), which allows to define e.g. lambda expression that returns String which is used for ComboBox items instead of the property from underlying data object.

The linked Forum discussion you found is about similar thing in our previous generation of the framework, there has been some renaming of the API here.

Tatu Lund
  • 9,949
  • 1
  • 12
  • 26