Composite Fields with CustomField

The CustomField is a way to create composite components as with CustomComponent, except that it implements the Field interface and inherits AbstractField, described in “Field Components”. A field allows editing a property value in the data model, and can be bound to data with Binder, as described in “Binding Data to Forms”.

A composite field class must implement initContent() method. It should return the content composite of the field.

Methods overriding setInternalValue() should call the superclass method.

Basic Use

Let us consider a simple custom switch button component that allows you to click a button to switch it “on” and “off”, as illustrated in A custom switch button field.

customfield basic

A custom switch button field

The field has Boolean value type, which the getType() returns. In initContent(), we initialize the button and the layout. Notice how we handle user interaction with the button to change the field value. We customize the setValue() method to reflect the state back to the user.

Java

  1. public class BooleanField extends CustomField<Boolean> {
  2. private final Button button = new Button("Off");
  3. private boolean value;
  4. @Override
  5. protected Component initContent() {
  6. button.addClickListener(event -> {
  7. setValue(!getValue());
  8. button.setCaption(getValue() ? "On" : "Off");
  9. });
  10. VerticalLayout layout = new VerticalLayout();
  11. layout.addComponent(new Label("Click the button"));
  12. layout.addComponent(button);
  13. return layout;
  14. }
  15. @Override
  16. public Boolean getValue() {
  17. return value;
  18. }
  19. @Override
  20. protected void doSetValue(Boolean value) {
  21. this.value = value;
  22. button.setCaption(value ? "On" : "Off");
  23. }
  24. }

We can now use the field in all the normal ways for a field:

Java

  1. // Create it
  2. BooleanField field = new BooleanField();
  3. // It's a field so we can set its value
  4. field.setValue(new Boolean(true));
  5. // ...and read the value
  6. Label value = new Label(field.getValue()?
  7. "Initially on" : "Initially off");
  8. // ...and handle value changes
  9. field.addValueChangeListener(event ->
  10. value.setValue(field.getValue()?
  11. "It's now on" : "It's now off"));