NativeSelect value and caption

I have a NativeSelect component called Car and it has two values as below

“1” - “Honda”
“2” - “Toyota”

When they click on the component, I want them to see “Honda” and “Toyota”.

But let’s say if they select “Honda”, I want the value “1” to be passed to the server and not the string “Honda”. Similarly, if they select “Toyota” then I want value “2”. Can I do it using NativeSelect? If so, how please?

Thanks

The value of a NativeSelect is the selected item’s itemID. So make sure, your item IDs are 1, 2, 3… and so on.
By default, the NativeSelect component uses the item ID as its caption. You can fix the caption with two different approaches. First one is creating a property to the container that will contain the car names. Then tell the NativeSelect to use the property value as the caption. This is done by using the setItemCaptionPropertyId method.

Second alternative, is to explicitly set caption values for specific items using the setItemCaption method.

IndexedContainer container = new IndexedContainer();
container.addContainerProperty("name", String.class, null);
container.addItem(1).getItemProperty("name").setValue("Honda");
container.addItem(2).getItemProperty("name").setValue("Toyota");
NativeSelect select = new NativeSelect();
select.setContainerDataSource(container);
select.setItemCaptionPropertyId("name");