Docs

Documentation versions (currently viewingVaadin 8)

Vaadin 8 reached End of Life on February 21, 2022. Discover how to make your Vaadin 8 app futureproof →

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.

public class BooleanField extends CustomField<Boolean> {
    private final Button button = new Button("Off");
    private boolean value;

    @Override
    protected Component initContent() {
        button.addClickListener(event -> {
            setValue(!getValue());
            button.setCaption(getValue() ? "On" : "Off");
        });

        VerticalLayout layout = new VerticalLayout();
        layout.addComponent(new Label("Click the button"));
        layout.addComponent(button);
        return layout;
    }

    @Override
    public Boolean getValue() {
        return value;
    }

    @Override
    protected void doSetValue(Boolean value) {
        this.value = value;
        button.setCaption(value ? "On" : "Off");
    }
}

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

// Create it
BooleanField field = new BooleanField();

// It's a field so we can set its value
field.setValue(new Boolean(true));

// ...and read the value
Label value = new Label(field.getValue()?
    "Initially on" : "Initially off");

// ...and handle value changes
field.addValueChangeListener(event ->
    value.setValue(field.getValue()?
        "It's now on" : "It's now off"));