com.vaadin.data.

Class Binder<BEAN>

  • Type Parameters:

    BEAN - the bean type

    All Implemented Interfaces:

    Serializable

    Direct Known Subclasses:

    BeanValidationBinder

    public class Binder<BEAN>
    extends Object
    implements Serializable

    Connects one or more Field components to properties of a backing data type such as a bean type. With a binder, input components can be grouped together into forms to easily create and update business objects with little explicit logic needed to move data between the UI and the data layers of the application.

    A binder is a collection of bindings, each representing the mapping of a single field, through converters and validators, to a backing property.

    A binder instance can be bound to a single bean instance at a time, but can be rebound as needed. This allows usage patterns like a master-details view, where a select component is used to pick the bean to edit.

    Bean level validators can be added using the withValidator(Validator) method and will be run on the bound bean once it has been updated from the values of the bound fields. Bean level validators are also run as part of writeBean(Object) and writeBeanIfValid(Object) if all field level validators pass.

    Note: For bean level validators, the bean must be updated before the validators are run. If a bean level validator fails in writeBean(Object) or writeBeanIfValid(Object), the bean will be reverted to the previous state before returning from the method. You should ensure that the getters/setters in the bean do not have side effects.

    Unless otherwise specified, Binder method arguments cannot be null.

    Since:

    8.0

    Author:

    Vaadin Ltd.

    See Also:

    Binder.BindingBuilder, Binder.Binding, HasValue, Serialized Form

    • Constructor Detail

      • Binder

        public Binder​(Class<BEAN> beanType)

        Creates a new binder that uses reflection based on the provided bean type to resolve bean properties.

        Parameters:

        beanType - the bean type to use, not null

      • Binder

        public Binder​(Class<BEAN> beanType,
                      boolean scanNestedDefinitions)

        Creates a new binder that uses reflection based on the provided bean type to resolve bean properties.

        Parameters:

        beanType - the bean type to use, not null

        scanNestedDefinitions - if true, scan for nested property definitions as well

        Since:

        8.2

    • Method Detail

      • handleFieldValueChange

        protected void handleFieldValueChange​(Binder.Binding<BEAN,​?> binding,
                                              HasValue.ValueChangeEvent<?> event)

        Informs the Binder that a value in Binding was changed. If readBean(Object) was used, this method will only validate the changed binding and ignore state of other bindings. If setBean(Object) was used, all pending changed bindings will be validated and non-changed ones will be ignored. The changed value will be written to the bean immediately, assuming that Binder-level validators also pass.

        Parameters:

        binding - the binding whose value has been changed

        event - the value change event

        Since:

        8.2

      • withPropertySet

        public static <BEAN> Binder<BEAN> withPropertySet​(PropertySet<BEAN> propertySet)

        Creates a binder using a custom PropertySet implementation for finding and resolving property names for bindInstanceFields(Object), bind(HasValue, String) and Binder.BindingBuilder.bind(String).

        This functionality is provided as static method instead of as a public constructor in order to make it possible to use a custom property set without creating a subclass while still leaving the public constructors focused on the common use cases.

        Type Parameters:

        BEAN - the bean type

        Parameters:

        propertySet - the property set implementation to use, not null.

        Returns:

        a new binder using the provided property set, not null

        See Also:

        Binder(), Binder(Class)

      • bind

        public <FIELDVALUE> Binder.Binding<BEAN,​FIELDVALUE> bind​(HasValue<FIELDVALUE> field,
                                                                       ValueProvider<BEAN,​FIELDVALUE> getter,
                                                                       Setter<BEAN,​FIELDVALUE> setter)

        Binds a field to a bean property represented by the given getter and setter pair. The functions are used to update the field value from the property and to store the field value to the property, respectively.

        Use the forField(HasValue) overload instead if you want to further configure the new binding.

        Note: Not all HasValue implementations support passing null as the value. For these the Binder will automatically change null to a null representation provided by HasValue.getEmptyValue(). This conversion is one-way only, if you want to have a two-way mapping back to null, use forField(HasValue) and Binder.BindingBuilder.withNullRepresentation(Object).

        When a bean is bound with setBean(Object), the field value is set to the return value of the given getter. The property value is then updated via the given setter whenever the field value changes. The setter may be null; in that case the property value is never updated and the binding is said to be read-only.

        If the Binder is already bound to some bean, the newly bound field is associated with the corresponding bean property as described above.

        The getter and setter can be arbitrary functions, for instance implementing user-defined conversion or validation. However, in the most basic use case you can simply pass a pair of method references to this method as follows:

         class Person {
             public String getName() { ... }
             public void setName(String name) { ... }
         }
        
         TextField nameField = new TextField();
         binder.bind(nameField, Person::getName, Person::setName);
         

        Note: when a null setter is given the field will be marked as read-only by invoking HasValue.setReadOnly(boolean).

        Type Parameters:

        FIELDVALUE - the value type of the field

        Parameters:

        field - the field to bind, not null

        getter - the function to get the value of the property to the field, not null

        setter - the function to write the field value to the property or null if read-only

        Returns:

        the newly created binding

      • bind

        public <FIELDVALUE> Binder.Binding<BEAN,​FIELDVALUE> bind​(HasValue<FIELDVALUE> field,
                                                                       String propertyName)

        Binds the given field to the property with the given name. The getter and setter of the property are looked up using a PropertySet.

        For a Binder created using the Binder(Class) constructor, introspection will be used to find a Java Bean property. If a JSR-303 bean validation implementation is present on the classpath, a BeanValidator is also added to the binding.

        The property must have an accessible getter method. It need not have an accessible setter; in that case the property value is never updated and the binding is said to be read-only.

        Type Parameters:

        FIELDVALUE - the value type of the field to bind

        Parameters:

        field - the field to bind, not null

        propertyName - the name of the property to bind, not null

        Returns:

        the newly created binding

        Throws:

        IllegalArgumentException - if the property name is invalid

        IllegalArgumentException - if the property has no accessible getter

        IllegalStateException - if the binder is not configured with an appropriate PropertySet

        See Also:

        bind(HasValue, ValueProvider, Setter)

      • setBean

        public void setBean​(BEAN bean)

        Binds the given bean to all the fields added to this Binder. A null value removes a currently bound bean.

        When a bean is bound, the field values are updated by invoking their corresponding getter functions. Any changes to field values are reflected back to their corresponding property values of the bean as long as the bean is bound.

        Note: Any change made in one of the bound fields runs validation for only the changed Binder.Binding, and additionally any bean level validation for this binder (bean level validators are added using withValidator(Validator). As a result, the bean set via this method is not guaranteed to always be in a valid state. This means also that possible StatusChangeListener and BinderValidationStatusHandler are called indicating a successful validation, even though some bindings can be in a state that would not pass validation. If bean validity is required at all times, readBean(Object) and writeBean(Object) should be used instead.

        After updating each field, the value is read back from the field and the bean's property value is updated if it has been changed from the original value by the field or a converter.

        Parameters:

        bean - the bean to edit, or null to remove a currently bound bean and clear bound fields

        See Also:

        readBean(Object), writeBean(Object), writeBeanIfValid(Object)

      • removeBean

        public void removeBean()

        Removes the currently set bean and clears bound fields. If there is no bound bean, does nothing.

        This is a shorthand for setBean(Object) with null bean.

      • readBean

        public void readBean​(BEAN bean)

        Reads the bound property values from the given bean to the corresponding fields.

        The bean is not otherwise associated with this binder; in particular its property values are not bound to the field value changes. To achieve that, use setBean(Object).

        Parameters:

        bean - the bean whose property values to read or null to clear bound fields

        See Also:

        setBean(Object), writeBeanIfValid(Object), writeBean(Object)

      • writeBean

        public void writeBean​(BEAN bean)
                       throws ValidationException

        Writes changes from the bound fields to the given bean if all validators (binding and bean level) pass.

        If any field binding validator fails, no values are written and a ValidationException is thrown.

        If all field level validators pass, the given bean is updated and bean level validators are run on the updated bean. If any bean level validator fails, the bean updates are reverted and a ValidationException is thrown.

        Parameters:

        bean - the object to which to write the field values, not null

        Throws:

        ValidationException - if some of the bound field values fail to validate

        See Also:

        writeBeanIfValid(Object), readBean(Object), setBean(Object)

      • writeBean

        public void writeBean​(BEAN bean,
                              Collection<Binder.Binding<BEAN,​?>> bindingsToWrite)
                       throws ValidationException

        Writes changes from the given bindings to the given bean if all validators (binding and bean level) pass.

        If any field binding validator fails, no values are written and a ValidationException is thrown.

        If all field level validators pass, the given bean is updated and bean level validators are run on the updated bean. If any bean level validator fails, the bean updates are reverted and a ValidationException is thrown.

        Parameters:

        bean - the object to which to write the field values, not null

        bindingsToWrite - Collection of bindings to use in writing the bean

        Throws:

        ValidationException - if some of the bound field values fail to validate

        IllegalArgumentException - if bindingsToWrite contains bindings not belonging to this Binder

        Since:

        8.24

        See Also:

        writeBeanIfValid(Object), writeBean(Object), readBean(Object), setBean(Object), writeChangedBindingsToBean(Object)

      • writeChangedBindingsToBean

        public void writeChangedBindingsToBean​(BEAN bean)
                                        throws ValidationException

        Writes changes from the changed bindings to the given bean if all validators (binding and bean level) pass. If the bean is the same instance where Binder read the bean, this method updates the bean with the changes.

        If any field binding validator fails, no values are written and a ValidationException is thrown.

        If all field level validators pass, the given bean is updated and bean level validators are run on the updated bean. If any bean level validator fails, the bean updates are reverted and a ValidationException is thrown.

        Parameters:

        bean - the object to which to write the field values, not null

        Throws:

        ValidationException - if some of the bound field values fail to validate

        Since:

        8.24

        See Also:

        writeBeanIfValid(Object), writeBean(Object), readBean(Object), setBean(Object)

      • getChangedBindings

        public Set<Binder.Binding<BEAN,​?>> getChangedBindings()

        Get the immutable Set of changed bindings.

        Returns:

        Immutable set of bindings.

        Since:

        8.24

        See Also:

        hasChanges()

      • writeBeanAsDraft

        public void writeBeanAsDraft​(BEAN bean)

        Writes successfully converted and validated changes from the bound fields to the bean even if there are other fields with non-validated changes.

        Parameters:

        bean - the object to which to write the field values, not null

        Since:

        8.10

        See Also:

        writeBean(Object), writeBeanIfValid(Object), readBean(Object), setBean(Object)

      • writeBeanAsDraft

        public void writeBeanAsDraft​(BEAN bean,
                                     boolean forced)

        Writes successfully converted changes from the bound fields bypassing all the Validation, or all fields passing conversion if forced = true. If the conversion fails, the value written to the bean will be null.

        Parameters:

        bean - the object to which to write the field values, not null

        forced - disable all Validators during write

        Since:

        8.11

        See Also:

        writeBean(Object), writeBeanIfValid(Object), readBean(Object), setBean(Object)

      • writeBeanIfValid

        public boolean writeBeanIfValid​(BEAN bean)

        Writes changes from the bound fields to the given bean if all validators (binding and bean level) pass.

        If any field binding validator fails, no values are written and false is returned.

        If all field level validators pass, the given bean is updated and bean level validators are run on the updated bean. If any bean level validator fails, the bean updates are reverted and false is returned.

        Parameters:

        bean - the object to which to write the field values, not null

        Returns:

        true if there was no validation errors and the bean was updated, false otherwise

        See Also:

        writeBean(Object), readBean(Object), setBean(Object)

      • restoreBeanState

        protected void restoreBeanState​(BEAN bean,
                                        Map<Binder.Binding<BEAN,​?>,​Object> oldValues)

        Restores the state of the bean from the given values. This method is used together with getBeanState(Object, Collection) to provide a way to revert changes in case the bean validation fails after save.

        Parameters:

        bean - the bean

        oldValues - the old values

        Since:

        8.2

      • getBeanState

        protected Map<Binder.Binding<BEAN,​?>,​Object> getBeanState​(BEAN bean,
                                                                              Collection<Binder.Binding<BEAN,​?>> bindings)

        Stores the state of the given bean. This method is used together with restoreBeanState(Object, Map) to provide a way to revert changes in case the bean validation fails after save.

        Parameters:

        bean - the bean to store the state of

        bindings - the bindings to store

        Returns:

        map from binding to value

        Since:

        8.2

      • validate

        public BinderValidationStatus<BEAN> validate()

        Validates the values of all bound fields and returns the validation status.

        If all field level validators pass, and setBean(Object) has been used to bind to a bean, bean level validators are run for that bean. Bean level validators are ignored if there is no bound bean or if any field level validator fails.

        Note: This method will attempt to temporarily apply all current changes to the bean and run full bean validation for it. The changes are reverted after bean validation.

        Returns:

        validation status for the binder

      • validate

        protected BinderValidationStatus<BEAN> validate​(boolean fireEvent)

        Validates the values of all bound fields and returns the validation status. This method can fire validation status events. Firing the events depends on the given boolean.

        Parameters:

        fireEvent - true to fire validation status events; false to not

        Returns:

        validation status for the binder

        Since:

        8.2

      • isValid

        public boolean isValid()

        Runs all currently configured field level validators, as well as all bean level validators if a bean is currently set with setBean(Object), and returns whether any of the validators failed.

        Note: Calling this method will not trigger status change events, unlike validate() and will not modify the UI. To also update error indicators on fields, use validate().isOk().

        Note: This method will attempt to temporarily apply all current changes to the bean and run full bean validation for it. The changes are reverted after bean validation.

        Returns:

        whether this binder is in a valid state

        Throws:

        IllegalStateException - if bean level validators have been configured and no bean is currently set

        See Also:

        validate()

      • getStatusLabel

        public Optional<Label> getStatusLabel()

        Gets the status label or an empty optional if none has been set.

        Returns:

        the optional status label

        See Also:

        setStatusLabel(Label)

      • addValueChangeListener

        public Registration addValueChangeListener​(HasValue.ValueChangeListener<?> listener)

        Adds field value change listener to all the fields in the binder.

        Added listener is notified every time whenever any bound field value is changed, i.e. the UI component value was changed, passed all the conversions and validations then propagated to the bound bean field. The same functionality can be achieved by adding a HasValue.ValueChangeListener to all fields in the Binder.

        The listener is added to all fields regardless of whether the method is invoked before or after field is bound.

        Parameters:

        listener - a field value change listener

        Returns:

        a registration for the listener

        See Also:

        HasValue.ValueChangeEvent, HasValue.ValueChangeListener

      • createBinding

        protected <FIELDVALUE,​TARGET> Binder.BindingBuilder<BEAN,​TARGET> createBinding​(HasValue<FIELDVALUE> field,
                                                                                                   Converter<FIELDVALUE,​TARGET> converter,
                                                                                                   BindingValidationStatusHandler handler)

        Creates a new binding with the given field.

        Type Parameters:

        FIELDVALUE - the value type of the field

        TARGET - the target data type

        Parameters:

        field - the field to bind, not null

        converter - the converter for converting between FIELDVALUE and TARGET types, not null

        handler - the handler to notify of status changes, not null

        Returns:

        the new incomplete binding

      • clearError

        protected void clearError​(HasValue<?> field)

        Clears the error condition of the given field, if any. The default implementation clears the component error of the field if it is a Component, otherwise does nothing.

        Parameters:

        field - the field with an invalid value

      • handleError

        protected void handleError​(HasValue<?> field,
                                   ValidationResult result)

        Handles a validation error emitted when trying to write the value of the given field. The default implementation sets the component error of the field if it is a Component, otherwise does nothing.

        Parameters:

        field - the field with the invalid value

        result - the validation error result

        Since:

        8.2

      • handleBinderValidationStatus

        protected void handleBinderValidationStatus​(BinderValidationStatus<BEAN> binderStatus)

        The default binder level status handler.

        Passes all field related results to the Binding status handlers. All other status changes are displayed in the status label, if one has been set with setStatusLabel(Label).

        Parameters:

        binderStatus - status of validation results from binding and/or bean level validators

      • hasChanges

        public boolean hasChanges()

        Check whether any of the bound fields' have uncommitted changes since last explicit call to readBean(Object), removeBean(), writeBean(Object) or writeBeanIfValid(Object). Unsuccessful write operations will not affect this value.

        Note that if you use setBean(Object) method, Binder tries to commit changes as soon as all validators have passed. Thus, when using this method with it seldom makes sense and almost always returns false.

        Return values for each case are compiled into the following table:
        After readBean, setBean or removeBean After valid user changes After invalid user changes After successful writeBean or writeBeanIfValid After unsuccessful writeBean or writeBeanIfValid
        A bean is currently bound false false true false no change
        No bean is currently bound false true true false no change

        Returns:

        whether any bound field's value has changed since last call to setBean, readBean, writeBean or writeBeanIfValid

        Since:

        8.24

      • hasChanges

        public boolean hasChanges​(Binder.Binding<BEAN,​?> binding)

        Checks whether a bound field has uncommitted changes.

        Parameters:

        binding - Binding to be checked

        Returns:

        true if field has been changed.

      • setReadOnly

        public void setReadOnly​(boolean readOnly)

        Sets the read only state to the given value for all current bindings.

        This is just a shorthand for calling Binder.Binding.setReadOnly(boolean) for all current bindings. It means that bindings added after this method call won't be set read-only.

        Parameters:

        readOnly - true to set the bindings to read-only, false to set them to read-write

      • getEventRouter

        protected EventRouter getEventRouter()

        Returns the event router for this binder.

        Returns:

        the event router, not null

      • configureBinding

        protected Binder.BindingBuilder<BEAN,​?> configureBinding​(Binder.BindingBuilder<BEAN,​?> binding,
                                                                       PropertyDefinition<BEAN,​?> definition)

        Configures the binding with the property definition definition before it's being bound.

        Parameters:

        binding - a binding to configure

        definition - a property definition information

        Returns:

        the new configured binding

      • bindInstanceFields

        public void bindInstanceFields​(Object objectWithMemberFields)

        Binds member fields found in the given object.

        This method processes all (Java) member fields whose type extends HasValue and that can be mapped to a property id. Property name mapping is done based on the field name or on a @PropertyId annotation on the field. All non-null unbound fields for which a property name can be determined are bound to the property name using Binder.BindingBuilder.bind(String).

        For example:

         public class MyForm extends VerticalLayout {
         private TextField firstName = new TextField("First name");
         @PropertyId("last")
         private TextField lastName = new TextField("Last name");
        
         MyForm myForm = new MyForm();
         ...
         binder.bindInstanceFields(myForm);
         
        This binds the firstName TextField to a "firstName" property in the item, lastName TextField to a "last" property.

        It's not always possible to bind a field to a property because their types are incompatible. E.g. custom converter is required to bind HasValue<String> and Integer property (that would be a case of "age" property). In such case, an attempt is made to get a suitable converter from a ConverterFactory but, if there is no match, an IllegalStateException will be thrown, unless the field has been configured manually before calling the bindInstanceFields(Object) method.

        It's always possible to do custom binding for any field: the bindInstanceFields(Object) method doesn't override existing bindings.

        Parameters:

        objectWithMemberFields - The object that contains (Java) member fields to bind

        Throws:

        IllegalStateException - if there are incompatible HasValue<T> and property types

        See Also:

        getConverterFactory()

      • getConverterFactory

        protected ConverterFactory getConverterFactory()

        Gets an instance of ConverterFactory that can be used to detect a suitable converter for bindings when presentation and model types are not compatible and a converter has not been explicitly configured. By default, returns a factory capable of handling standard converters. Subclasses can override this method to provide additional or customized conversion rules by creating a completely new factory implementation or composing with the default one.

        Returns:

        an instance of ConverterFactory, never null.

      • getFields

        public Stream<HasValue<?>> getFields()

        Returns the fields this binder has been bound to.

        Returns:

        the fields with bindings

        Since:

        8.1

      • removeBinding

        public void removeBinding​(HasValue<?> field)

        Finds and removes all Bindings for the given field. Note that this method and other overloads of removeBinding method do not reset component errors that might have been added to the field and do not remove required indicator of the field no matter if it was set by Binder or not. To reset component errors, field.setComponentError(null) should be called and to remove required indicator, field.setRequiredIndicatorVisible(false) should be called.

        Parameters:

        field - the field to remove from bindings

        Since:

        8.2

        See Also:

        AbstractComponent.setComponentError(com.vaadin.server.ErrorMessage), AbstractComponent.setRequiredIndicatorVisible(boolean)

      • removeBindingInternal

        protected void removeBindingInternal​(Binder.Binding<BEAN,​?> binding)

        Removes (internally) the Binding from the bound properties map (if present) and from the list of Bindings. Note that this DOES NOT remove the ValueChangeListener that the Binding might have registered with any HasValues or decouple the Binder from within the Binding. To do that, use Binder.Binding.unbind() This method should just be used for internal cleanup.

        Parameters:

        binding - The Binding to remove from the binding map

        Since:

        8.2

      • setValidatorsDisabled

        public void setValidatorsDisabled​(boolean validatorsDisabled)

        Control whether validators including bean level validators are disabled or enabled globally for this Binder.

        Parameters:

        validatorsDisabled - Boolean value

        Since:

        8.11

      • isValidatorsDisabled

        public boolean isValidatorsDisabled()

        Returns if the validators including bean level validators are disabled or enabled for this Binder.

        Returns:

        Boolean value

        Since:

        8.11

      • setChangeDetectionEnabled

        public void setChangeDetectionEnabled​(boolean changeDetectionEnabled)

        Sets change/revert detection enabled or disabled. When set to true, any binding that is first changed and then reverted to its original value will be removed from the list of changed bindings. By default, Objects.equals(Object, Object) is used for value comparison, but it can be overridden on binding level using Binder.BindingBuilder.withEqualityPredicate(SerializableBiPredicate).

        Parameters:

        changeDetectionEnabled - Boolean value