Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
How to use Converter in NativeSelect
Hi, I have a Boolean (or enum) data and want to display in NativeSelect in String model:
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
String YES = "Yes";
String NO ="No";
final NativeSelect select = new NativeSelect("Choose");
select.addItems(Arrays.asList(new String[]{YES, NO}));
select.setNullSelectionAllowed(false);
Boolean dateModelValue = Boolean.FALSE;
// StringToBooleanConverter converter = new StringToBooleanConverter("Yes","No");
// select.setValue(converter);
/* // case 1
select.setConverter(Boolean.class);
select.setValue(dateModelValue);
// case 2
select.setConverter(String.class);
select.setValue(dateModelValue);
*/
// case 3
select.setConverter(Boolean.class);
select.setValue(NO);
// case 4
/* select.setConverter(String.class);
select.setValue(NO);
*/
select.addValueChangeListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Notification.show(String.format("value=%s, converted value=%s", select.getValue(), select.getConvertedValue()));
}
});
layout.addComponent(select);
}
I assume that setConvert(...) could support vaule return Boolean and converted value String, or in contrast.
1. public void setConverter(Class<?> datamodelType) - test 4 cases above, the results are not as wanted.
2. setConverter(Converter<T, ?> converter) - report StringToBooleanConverter is not applicable for the arguments.
So my question is whether setConvert(...) supports NativeSelect for the purpose. if yes, how.
Hi,
setConverter(Class<?> datamodelType) takes the converter from a ConvertFactory. In case of Boolean.class the StringToBooleanConverter is used.
StringToBooleanConverter by default map the strings "true" and "false" to the equivalent boolean values, but you can change this mapping
new StringToBooleanConverter(YES, NO);
In case of NativeSelect you should use an unchecked assingment in setConverter(...) because NativeSelect, due to type parameter, expects a Converter<Object, ?> whereas StringToBooleanConverter is a Converter<String, Boolean>
Converter converter = new StringToBooleanConverter(YES, NO);
select.setConverter(converter);
HTH
Marco