The full solution also involves database lookup, so client-side is out. I also prefer to write as little client-side code as possible.
My first thought was a converter, but I assumed I would have to fight with Vaadin.
I’ve created a small test program to test.
In the program below, I let the bean value start as “mo”, and I had assumed Vaadin would convert that to “Monday” as soon as it was displayed. That did not happen, which surprised me.
This means the converter behaves like I want; It should only convert when user changes the value.
Earlier I’ve had to fight against “writeback”, where if the bean has 3.14159265359, and I had a converter that displays it as, “3.14”, Vaadin would “write back” 3.14 to the bean as well.
Ah, the difference is that in MyWeekdayConverter I adjust the value in convertToModel, while in my 3.14159265359 case I adjust the value in convertToPresentation as well…
So, for my current use-case it looks like I can use a Converter, but Vaadin’s conversion model is still questionable.
package com.ec.traveller;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.Result;
import com.vaadin.flow.data.binder.ValueContext;
import com.vaadin.flow.data.converter.Converter;
import com.vaadin.flow.router.Route;
@Route("/testConverter")
public class TestConverter extends VerticalLayout {
static class MyWeekdayConverter implements Converter<String, String> {
static String[] weekdays = { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" };
@Override
public Result<String> convertToModel(String value, ValueContext context) {
for(String day : weekdays) {
if(day.startsWith(value)) {
return Result.ok(day.substring(0, 1).toUpperCase() + day.substring(1));
}
}
return Result.ok(value);
}
@Override
public String convertToPresentation(String value, ValueContext context) {
return value;
}
}
static class Info {
String weekday;
public String getWeekday() { return weekday; }
public void setWeekday(String weekday) { this.weekday = weekday;}
}
public TestConverter() {
var weekdayField = new TextField("Weekday");
var binder = new Binder<Info>(Info.class);
binder.forField(weekdayField)
.withNullRepresentation("")
.withConverter(new MyWeekdayConverter())
.bind(Info::getWeekday, Info::setWeekday);
add(weekdayField);
var info = new Info();
info.setWeekday("mo");
binder.setBean(info);
}
}