Search code examples
vaadinvaadin10

How do I bind Character to a TextField?


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.

Solution

  • 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;
        }
    
    }