1

I've found an example of how to bind Integer to a TextField:

Binder<Person> b = new Binder<>();
b.forField(ageField)
    .withNullRepresentation("")
    .withConverter(new StringToIntegerConverter("Must be valid integer !"))
    .withValidator(integer -> integer > 0, "Age must be positive")
    .bind(p -> p.getAge(), (p, i) -> p.setAge(i));

The problem is - there is no StringToCharacterConverter and if have an error if I bind fields as is. The error is:

Property type 'java.lang.Character' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.
John
  • 467
  • 1
  • 6
  • 23

1 Answers1

3

You need to implement custom converter, here is very simplified version of what could be StringToCharacterConverter for getting the pattern what the they look like:

public class StringToCharacterConverter implements Converter<String,Character> {

    @Override
    public Result<Character> convertToModel(String value, ValueContext context) {
        if (value == null) {
            return Result.ok(null);
        }

        value = value.trim();

        if (value.isEmpty()) {
            return Result.ok(null);
        } else if (value.length() == 1) {
            Character character = value.charAt(0);
            return Result.ok(character);
        } else {
            return Result.error("Error message here");
        }
    }

    @Override
    public String convertToPresentation(Character value, ValueContext context) {
        String string = value.toString();
        return string;
    }

}
Tatu Lund
  • 9,949
  • 1
  • 12
  • 26
  • Thank you so much. P.S. I also found similar code on github [StringToCharacterConverter](https://github.com/athomaspascal/usersasadminv2/blob/1a1ef2e869c7644cf03488d9a7b12f4a3c44cb0f/src/main/java/org/vaadin/data/converter/StringToCharacterConverter.java) – John Jul 31 '18 at 12:01