Documentation

Documentation versions (currently viewingVaadin 24)

Using API Helpers to Define Component Properties

How to use PropertyDescriptors to define a property name and default value.

The PropertyDescriptor interface and associated PropertyDescriptors helper class simplify managing attributes and properties in a component.

You can use PropertyDescriptors to define a property name and default value in a single place, and then use the descriptor from the setter and getter methods.

Example: Using the PropertyDescriptors.propertyWithDefault() method to define the default property value.

@Tag("input")
public class TextField extends Component {
    private static PropertyDescriptor<String, String>
        VALUE = PropertyDescriptors
                .propertyWithDefault("value", "");

    public String getValue() {
        return get(VALUE);
    }
    public void setValue(String value) {
        set(VALUE, value);
    }
}

Your component API must meet the following requirements to function correctly for a given property, such as the value of an input field:

  • The getter and setter should use the same property or attribute.

  • The default value should be handled appropriately.

  • The getter return value should be either:

    • the type used by the setter, for example String for an input value, or

    • an optional version of the type used by the setter if the property isn’t mandatory; for example, Optional<String>.

PropertyDescriptors automatically take these requirements into consideration.

PropertyDescriptor Interface

You create PropertyDescriptor instances using the helper methods that are available in the PropertyDescriptors class.

Different helper methods are available, depending on how you want your component to work:

  • PropertyDescriptors.propertyWithDefault() maps to an element property with a given default value.

  • PropertyDescriptors.attributeWithDefault() maps to an element attribute with a given default value.

  • PropertyDescriptors.optionalAttributeWithDefault() maps to an element attribute with a given default value, but returns an empty Optional when the default value is set.

Example: Using the PropertyDescriptors.optionalAttributeWithDefault() method for a non-mandatory placeholder in a TextField.

@Tag("input")
public class TextField extends Component {
  private static PropertyDescriptor<String,
    Optional<String>> PLACEHOLDER = PropertyDescriptors
       .optionalAttributeWithDefault("placeholder", "");

  public Optional<String> getPlaceholder() {
    return get(PLACEHOLDER);
  }
  public void setPlaceholder(String placeholder) {
      set(PLACEHOLDER, placeholder);
  }
}
Note
The default value used in all PropertyDescriptors methods should match the value in the browser when the attribute or property is not set. Otherwise, when the user sets the value to the default value, the value isn’t correctly sent to the browser.

4540DCE0-BF2A-4D88-B91E-DA2D1EAD80BC