Creating your own converter for String - MyType conversion

If you have custom types that you want to represent using the built in field components, you can easily create your own converter to take care of converting between your own type and the native data type of the field.

A sample custom type, in this case a Name object with separate fields for first and last name.

Java

  1. public class Name {
  2. private String firstName;
  3. private String lastName;
  4. public Name(String firstName, String lastName) {
  5. this.firstName = firstName;
  6. this.lastName = lastName;
  7. }
  8. public String getFirstName() {
  9. return firstName;
  10. }
  11. public void setFirstName(String firstName) {
  12. this.firstName = firstName;
  13. }
  14. public String getLastName() {
  15. return lastName;
  16. }
  17. public void setLastName(String lastName) {
  18. this.lastName = lastName;
  19. }
  20. }

A converter for the name, assuming the parts are separated with a space and that there are only two parts of a name.

Java

  1. public class StringToNameConverter implements Converter<String, Name> {
  2. public Name convertToModel(String text, Locale locale)
  3. throws ConversionException {
  4. if (text == null) {
  5. return null;
  6. }
  7. String[] parts = text.split(" ");
  8. if (parts.length != 2) {
  9. throw new ConversionException("Can not convert text to a name: " + text);
  10. }
  11. return new Name(parts[0], parts[1]);
  12. }
  13. public String convertToPresentation(Name name, Locale locale)
  14. throws ConversionException {
  15. if (name == null) {
  16. return null;
  17. } else {
  18. return name.getFirstName() + " " + name.getLastName();
  19. }
  20. }
  21. public Class<Name> getModelType() {
  22. return Name.class;
  23. }
  24. public Class<String> getPresentationType() {
  25. return String.class;
  26. }
  27. }

Hooking up the Name type and its Converter to a TextField can then be done like this

Java

  1. Name name = new Name("Rudolph", "Reindeer");
  2. final TextField textField = new TextField("Name");
  3. textField.setConverter(new StringToNameConverter());
  4. textField.setConvertedValue(name);
  5. addComponent(textField);
  6. addComponent(new Button("Submit value", new ClickListener() {
  7. public void buttonClick(ClickEvent event) {
  8. try {
  9. Name name = (Name) textField.getConvertedValue();
  10. Notification.show(
  11. "First name: " + name.getFirstName() +
  12. "<br />Last name: " + name.getLastName());
  13. } catch (ConversionException e) {
  14. Notification.show(e.getCause().getMessage());
  15. }
  16. }
  17. }));