com.vaadin.flow.data.binder.
Class Binder<BEAN>
Type Parameters:
BEAN
- the bean type
All Implemented Interfaces:
Direct Known Subclasses:
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:
1.0.
Author:
Vaadin Ltd
See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interface
Represents the binding between a field and a data property.
static interface
Creates a binding between a field and a data property.
protected static class
An internal implementation of
BindingBuilder
.protected static class
An internal implementation of
Binding
. -
Constructor Summary
ConstructorsModifierConstructorDescriptionBinder()
Creates a new binder without support for creating bindings based on property names.
protected
Binder
(PropertySet<BEAN> propertySet) Creates a binder using a custom
PropertySet
implementation for finding and resolving property names forbindInstanceFields(Object)
,bind(HasValue, String)
andBinder.BindingBuilder.bind(String)
.Creates a new binder that uses reflection based on the provided bean or record type to resolve its properties.
Creates a new binder that uses reflection based on the provided bean or record type to resolve its properties.
-
Method Summary
Modifier and TypeMethodDescriptionprotected <T> Registration
addListener
(Class<T> eventType, SerializableConsumer<T> method) Adds a listener to the binder.
addStatusChangeListener
(StatusChangeListener listener) Adds status change listener to the binder.
addValueChangeListener
(HasValue.ValueChangeListener<? super HasValue.ValueChangeEvent<?>> listener) Adds field value change listener to all the fields in the binder.
<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.
<FIELDVALUE>
Binder.Binding<BEAN,FIELDVALUE> Binds the given field to the property with the given name.
void
bindInstanceFields
(Object objectWithMemberFields) Binds member fields found in the given object.
<FIELDVALUE>
Binder.Binding<BEAN,FIELDVALUE> bindReadOnly
(HasValue<?, FIELDVALUE> field, ValueProvider<BEAN, FIELDVALUE> getter) Binds a field to a bean property represented by the given getter.
<FIELDVALUE>
Binder.Binding<BEAN,FIELDVALUE> bindReadOnly
(HasValue<?, FIELDVALUE> field, String propertyName) Binds the given field to the property with the given name.
protected void
clearError
(HasValue<?, ?> field) Clears the error condition of the given field, if any.
protected Binder.BindingBuilder<BEAN,
?> configureBinding
(Binder.BindingBuilder<BEAN, ?> binding, PropertyDefinition<BEAN, ?> definition) Configures the
binding
with the property definitiondefinition
before it's being bound.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.
protected <FIELDVALUE,
TARGET>
Binder.BindingBuilder<BEAN,TARGET> doCreateBinding
(HasValue<?, FIELDVALUE> field, Converter<FIELDVALUE, TARGET> converter, BindingValidationStatusHandler handler) <FIELDVALUE>
Binder.BindingBuilder<BEAN,FIELDVALUE> Creates a new binding for the given field.
<FIELDVALUE>
Binder.BindingBuilder<BEAN,FIELDVALUE> forMemberField
(HasValue<?, FIELDVALUE> field) Creates a new binding for the given field.
getBean()
Returns the bean that has been bound with
bind(com.vaadin.flow.component.HasValue<?, FIELDVALUE>, com.vaadin.flow.function.ValueProvider<BEAN, FIELDVALUE>, com.vaadin.flow.data.binder.Setter<BEAN, FIELDVALUE>)
, or null if a bean is not currently bound.protected Map<Binder.Binding<BEAN,
?>, Object> getBeanState
(BEAN bean, Collection<Binder.Binding<BEAN, ?>> bindings) Stores the state of the given bean.
getBinding
(String propertyName) Gets the binding for a property name.
Gets the current exception handler.
protected Collection<Binder.BindingImpl<BEAN,
?, ?>> Returns the bindings for this binder.
Set<Binder.Binding<BEAN,
?>> Get the immutable Set of changed bindings.
protected ConverterFactory
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.Returns the fields this binder has been bound to.
Gets the status label or an empty optional if none has been set.
Gets the validation error of this form.
Gets the status handler of this form.
protected void
handleBinderValidationStatus
(BinderValidationStatus<BEAN> binderStatus) The default binder level status handler.
protected void
handleError
(HasValue<?, ?> field, ValidationResult result) Handles a validation error emitted when trying to write the value of the given field.
protected void
handleFieldValueChange
(Binder.Binding<BEAN, ?> binding) Informs the Binder that a value in Binding was changed.
protected void
handleValidationStatus
(BindingValidationStatus<?> status) Default
BindingValidationStatusHandler
functional method implementation.boolean
Check whether any of the bound fields' have uncommitted changes since last explicit call to
readBean(Object)
,removeBean()
,writeBean(Object)
orwriteBeanIfValid(Object)
.boolean
hasChanges
(Binder.Binding<BEAN, ?> binding) Checks whether a bound field has uncomitted changes.
boolean
Returns if change/revert detection is enabled.
boolean
Returns the Binder-level setting for enabling default validators of bound fields.
boolean
Returns if the bound fields implementing
HasValidator
subscribe for field'sValidationStatusChangeEvent
s and willvalidate
upon receiving them.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.boolean
Returns if the validators including bean level validators are disabled or enabled for this Binder.
void
Reads the bound property values from the given bean or record to the corresponding fields.
void
readRecord
(BEAN record) Reads the bound property values from the given record to the corresponding fields.
void
Refreshes the fields values by reading them again from the currently associated bean via invoking their corresponding value provider methods.
void
Removes the currently set bean and clears bound fields.
void
removeBinding
(HasValue<?, ?> field) Finds and removes all Bindings for the given field.
void
removeBinding
(Binder.Binding<BEAN, ?> binding) Removes the given Binding from this Binder.
void
removeBinding
(String propertyName) Finds and removes the Binding for the given property name.
protected void
removeBindingInternal
(Binder.Binding<BEAN, ?> binding) Removes (internally) the
Binding
from the bound properties map (if present) and from the list ofBinding
s.protected void
restoreBeanState
(BEAN bean, Map<Binder.Binding<BEAN, ?>, Object> oldValues) Restores the state of the bean from the given values.
void
Binds the given bean to all the fields added to this Binder.
void
Sets a
handler
to customize theRuntimeException
thrown by delegates (likeSetter
,ValueProvider
,HasValue
) used insideBinder
to be able to identify the bound field.void
setChangeDetectionEnabled
(boolean changeDetectionEnabled) Sets change/revert detection enabled or disabled.
void
setDefaultValidatorsEnabled
(boolean defaultValidatorsEnabled) Sets up the Binder to either enable or disable the default field validators (e.g.
void
setFieldsValidationStatusChangeListenerEnabled
(boolean fieldsValidationStatusChangeListenerEnabled) Control whether bound fields implementing
HasValidator
subscribe for field'sValidationStatusChangeEvent
s and willvalidate
upon receiving them.void
setReadOnly
(boolean readOnly) Sets the read only state to the given value for all currently bound fields.
void
setStatusLabel
(HasText statusLabel) Sets the label to show the binder level validation errors not related to any specific field.
void
Sets the validation error handler to update error status for fields when the user input is validated.
void
setValidationStatusHandler
(BinderValidationStatusHandler<BEAN> statusHandler) Sets the status handler to track form status changes.
void
setValidatorsDisabled
(boolean validatorsDisabled) Control whether validators including bean level validators are disabled or enabled globally for this Binder.
validate()
Validates the values of all bound fields and returns the validation status.
protected BinderValidationStatus<BEAN>
validate
(boolean fireEvent) Validates the values of all bound fields and returns the validation status.
static <BEAN> Binder<BEAN>
withPropertySet
(PropertySet<BEAN> propertySet) Creates a binder using a custom
PropertySet
implementation for finding and resolving property names forbindInstanceFields(Object)
,bind(HasValue, String)
andBinder.BindingBuilder.bind(String)
.withValidator
(Validator<? super BEAN> validator) Adds an bean level validator.
withValidator
(SerializablePredicate<BEAN> predicate, ErrorMessageProvider errorMessageProvider) A convenience method to add a validator to this binder using the
Validator.from(SerializablePredicate, ErrorMessageProvider)
factory method.withValidator
(SerializablePredicate<BEAN> predicate, String message) A convenience method to add a validator to this binder using the
Validator.from(SerializablePredicate, String)
factory method.void
Writes changes from the bound fields to the given bean if all validators (binding and bean level) pass.
void
writeBean
(BEAN bean, Collection<Binder.Binding<BEAN, ?>> bindingsToWrite) Writes changes from the given bindings to the given bean if all validators (binding and bean level) pass.
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.
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.
boolean
writeBeanIfValid
(BEAN bean) Writes changes from the bound fields to the given bean if all validators (binding and bean level) pass.
void
Writes changes from the changed bindings to the given bean if all validators (binding and bean level) pass.
Writes values from the bound fields to a new record instance if all validators (binding and bean level) pass.
-
Constructor Details
-
Binder
Creates a binder using a custom
PropertySet
implementation for finding and resolving property names forbindInstanceFields(Object)
,bind(HasValue, String)
andBinder.BindingBuilder.bind(String)
.Parameters:
propertySet
- the property set implementation to use, notnull
. -
Binder
Creates a new binder that uses reflection based on the provided bean or record type to resolve its properties. Nested properties are resolved lazily, when bound to a field.
Parameters:
beanType
- the bean type to use, notnull
-
Binder
public Binder()Creates a new binder without support for creating bindings based on property names. Use an alternative constructor, such as
Binder(Class)
, to create a binder that support creating bindings based on instance fields throughbindInstanceFields(Object)
, or based on a property name throughbind(HasValue, String)
orBinder.BindingBuilder.bind(String)
. -
Binder
Creates a new binder that uses reflection based on the provided bean or record type to resolve its properties. If
scanNestedDefinitions
is true, nested properties are detected eagerly. Otherwise, they will be discovered lazily when the property is bound to a field.Parameters:
beanType
- the bean type to use, notnull
scanNestedDefinitions
- iftrue
, scan for nested property definitions as well
-
-
Method Details
-
withPropertySet
Creates a binder using a custom
PropertySet
implementation for finding and resolving property names forbindInstanceFields(Object)
,bind(HasValue, String)
andBinder.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 typeParameters:
propertySet
- the property set implementation to use, notnull
.Returns:
a new binder using the provided property set, not
null
See Also:
-
handleFieldValueChange
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. IfsetBean(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 -
getBean
Returns the bean that has been bound with
bind(com.vaadin.flow.component.HasValue<?, FIELDVALUE>, com.vaadin.flow.function.ValueProvider<BEAN, FIELDVALUE>, com.vaadin.flow.data.binder.Setter<BEAN, FIELDVALUE>)
, or null if a bean is not currently bound.Returns:
the currently bound bean if any
-
forField
Creates a new binding for the given field. The returned builder may be further configured before invoking
Binder.BindingBuilder.bind(ValueProvider, Setter)
which completes the binding. UntilBinding.bind
is called, the binding has no effect.Note: Not all
HasValue
implementations support passingnull
as the value. For these the Binder will automatically changenull
to a null representation provided byHasValue.getEmptyValue()
. This conversion is one-way only, if you want to have a two-way mapping back tonull
, useBinder.BindingBuilder.withNullRepresentation(Object)
.Type Parameters:
FIELDVALUE
- the value type of the fieldParameters:
field
- the field to be bound, not nullReturns:
the new binding
See Also:
-
forMemberField
public <FIELDVALUE> Binder.BindingBuilder<BEAN,FIELDVALUE> forMemberField(HasValue<?, FIELDVALUE> field) Creates a new binding for the given field. The returned builder may be further configured before invoking
bindInstanceFields(Object)
. Unlike with theforField(HasValue)
method, no explicit call toBinder.BindingBuilder.bind(String)
is needed to complete this binding in the case that the name of the field matches a field name found in the bean.Type Parameters:
FIELDVALUE
- the value type of the fieldParameters:
field
- the field to be bound, not nullReturns:
the new binding builder
See Also:
-
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 passingnull
as the value. For these the Binder will automatically changenull
to a null representation provided byHasValue.getEmptyValue()
. This conversion is one-way only, if you want to have a two-way mapping back tonull
, useforField(HasValue)
andBinder.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 fieldParameters:
field
- the field to bind, not nullgetter
- the function to get the value of the property to the field, not nullsetter
- the function to write the field value to the property or null if read-onlyReturns:
the newly created binding
-
bindReadOnly
public <FIELDVALUE> Binder.Binding<BEAN,FIELDVALUE> bindReadOnly(HasValue<?, FIELDVALUE> field, ValueProvider<BEAN, FIELDVALUE> getter) Binds a field to a bean property represented by the given getter. The function is used to update the field value from the property. The field value is not written back to the bean so the binding is read-only.
Use the
forField(HasValue)
overload instead if you want to further configure the new binding.Note: Not all
HasValue
implementations support passingnull
as the value. For these the Binder will automatically changenull
to a null representation provided byHasValue.getEmptyValue()
. This conversion is one-way only, if you want to have a two-way mapping back tonull
, useforField(HasValue)
andBinder.BindingBuilder.withNullRepresentation(Object)
.When a bean is bound with
setBean(Object)
, the field value is set to the return value of the given getter.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 can be arbitrary function, 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() { ... } } TextField nameField = new TextField(); binder.bindReadOnly(nameField, Person::getName);
Note: the field will be marked as read-only by invoking (
HasValue.setReadOnly(boolean)
.Type Parameters:
FIELDVALUE
- the value type of the fieldParameters:
field
- the field to bind, not nullgetter
- the function to get the value of the property to the field, not nullReturns:
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 theBinder(Class)
constructor, introspection will be used to find a Java Bean property. If a JSR-303 bean validation implementation is present on the classpath, aBeanValidator
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. Nested properties support depends on the
PropertySet
type used to build theBinder
. If support is available, for example using the defaultBeanPropertySet
, nested property are supported and can be referenced using the bean path, starting from the root class, for example 'address.streetName'. All intermediate getters must exist (e.g.getAddress()
), and should never return null, otherwise binding will fail.Type Parameters:
FIELDVALUE
- the value type of the field to bindParameters:
field
- the field to bind, not nullpropertyName
- the name of the property to bind, not nullReturns:
the newly created binding
Throws:
IllegalArgumentException
- if the property name is invalidIllegalArgumentException
- if the property has no accessible getterIllegalStateException
- if the binder is not configured with an appropriatePropertySet
See Also:
-
bindReadOnly
public <FIELDVALUE> Binder.Binding<BEAN,FIELDVALUE> bindReadOnly(HasValue<?, FIELDVALUE> field, String propertyName) Binds the given field to the property with the given name. The getter of the property is looked up using a
PropertySet
. The field value is not written back to the bean so the binding is read-only.For a
Binder
created using theBinder(Class)
constructor, introspection will be used to find a Java Bean property. If a JSR-303 bean validation implementation is present on the classpath, aBeanValidator
is also added to the binding.The property must have an accessible getter method. Nested properties support depends on the
PropertySet
type used to build theBinder
. If support is available, for example using the defaultBeanPropertySet
, nested property are supported and can be referenced using the bean path, starting from the root class, for example 'address.streetName'. All intermediate getters must exist (e.g.getAddress()
), and should never return null, otherwise binding will fail.Type Parameters:
FIELDVALUE
- the value type of the field to bindParameters:
field
- the field to bind, not nullpropertyName
- the name of the property to bind, not nullReturns:
the newly created binding
Throws:
IllegalArgumentException
- if the property name is invalidIllegalArgumentException
- if the property has no accessible getterIllegalStateException
- if the binder is not configured with an appropriatePropertySet
See Also:
-
setBean
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 usingwithValidator(Validator)
. As a result, the bean set via this method is not guaranteed to always be in a valid state. This means also that possibleStatusChangeListener
andBinderValidationStatusHandler
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)
andwriteBean(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, ornull
to remove a currently bound bean and clear bound fieldsThrows:
IllegalStateException
- if the Binder's model type is recordSee Also:
-
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)
withnull
bean. -
readBean
Reads the bound property values from the given bean or record to the corresponding fields.
The bean or record 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 or record whose property values to read ornull
to clear bound fieldsSee Also:
-
readRecord
Reads the bound property values from the given record to the corresponding fields.
The record is not otherwise associated with this binder; in particular its property values are not bound to the field value changes.
Parameters:
record
- the record whose property values to read ornull
to clear bound fieldsThrows:
IllegalArgumentException
- if the given object's type is not a recordSee Also:
-
refreshFields
public void refreshFields()Refreshes the fields values by reading them again from the currently associated bean via invoking their corresponding value provider methods.
If no bean is currently associated with this binder (
setBean(Object)
has not been called before invoking this method), the bound fields will be cleared. -
writeBean
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, notnull
Throws:
ValidationException
- if some of the bound field values fail to validateSee Also:
-
writeBean
public void writeBean(BEAN bean, Collection<Binder.Binding<BEAN, ?>> bindingsToWrite) throws ValidationExceptionWrites 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, notnull
bindingsToWrite
- Collection of bindings to use in writing the beanThrows:
ValidationException
- if some of the bound field values fail to validateIllegalArgumentException
- if bindingsToWrite contains bindings not belonging to this BinderSee Also:
-
writeChangedBindingsToBean
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, notnull
Throws:
ValidationException
- if some of the bound field values fail to validateSee Also:
-
getChangedBindings
Get the immutable Set of changed bindings.
Returns:
Immutable set of bindings.
See Also:
-
writeBeanAsDraft
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, notnull
See Also:
-
writeBeanAsDraft
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, notnull
forced
- disable all Validators during writeSee Also:
-
writeBeanIfValid
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, notnull
Returns:
true
if there was no validation errors and the bean was updated,false
otherwiseSee Also:
-
writeRecord
Writes values from the bound fields to a new record instance if all validators (binding and bean level) pass. This method can only be used if Binder was originally configured to use a record type.
If any field binding validator fails, no values are written and a
ValidationException
is thrown.If all field level validators pass, a record is intanciated and bean level validators are run on the new record. If any bean level validator fails a
ValidationException
is thrown.Returns:
a record instance with current values
Throws:
ValidationException
- if some of the bound field values fail to validateIllegalStateException
- if a record component does not have a binding, or if the Binder's model type is beanIllegalArgumentException
- if record instantiation fails for any reasonSee Also:
-
restoreBeanState
Restores the state of the bean from the given values.
Parameters:
bean
- the beanoldValues
- the old values -
getBeanState
protected Map<Binder.Binding<BEAN,?>, getBeanStateObject> (BEAN bean, Collection<Binder.Binding<BEAN, ?>> bindings) Stores the state of the given bean.
Parameters:
bean
- the bean to store the state ofbindings
- the bindings to storeReturns:
map from binding to value
-
withValidator
Adds an bean level validator.
Bean level validators are applied on the bean instance after the bean is updated. If the validators fail, the bean instance is reverted to its previous state.
Parameters:
validator
- the validator to add, not nullReturns:
this binder, for chaining
See Also:
-
withValidator
A convenience method to add a validator to this binder using the
Validator.from(SerializablePredicate, String)
factory method.Bean level validators are applied on the bean instance after the bean is updated. If the validators fail, the bean instance is reverted to its previous state.
Parameters:
predicate
- the predicate performing validation, not nullmessage
- the error message to report in case validation failureReturns:
this binder, for chaining
See Also:
-
withValidator
public Binder<BEAN> withValidator(SerializablePredicate<BEAN> predicate, ErrorMessageProvider errorMessageProvider) A convenience method to add a validator to this binder using the
Validator.from(SerializablePredicate, ErrorMessageProvider)
factory method.Bean level validators are applied on the bean instance after the bean is updated. If the validators fail, the bean instance is reverted to its previous state.
Parameters:
predicate
- the predicate performing validation, not nullerrorMessageProvider
- the provider to generate error messages, not nullReturns:
this binder, for chaining
See Also:
-
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
Validates the values of all bound fields and returns the validation status. This method can skip firing the event, based on the given
boolean
.Parameters:
fireEvent
-true
to fire validation status events;false
to notReturns:
validation status for the binder
-
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, usevalidate().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 setSee Also:
-
setDefaultValidatorsEnabled
public void setDefaultValidatorsEnabled(boolean defaultValidatorsEnabled) Sets up the Binder to either enable or disable the default field validators (e.g. min/max validators in DatePicker) of all bound fields. This Binder-level setting can be overridden for each binding via either the binding object itself, or the binding builder.
Defaults to true.
Parameters:
defaultValidatorsEnabled
- true to enable default validators of bound fields, false to disable them -
isDefaultValidatorsEnabled
public boolean isDefaultValidatorsEnabled()Returns the Binder-level setting for enabling default validators of bound fields.
Returns:
true if default validators of bound fields are enabled, false if they are disabled
-
setStatusLabel
Sets the label to show the binder level validation errors not related to any specific field.
Only the one validation error message is shown in this label at a time.
This is a convenience method for
setValidationStatusHandler(BinderValidationStatusHandler)
, which means that this method cannot be used after the handler has been set. Also the handler cannot be set after this label has been set.Parameters:
statusLabel
- the status label to setSee Also:
-
getStatusLabel
Gets the status label or an empty optional if none has been set.
Returns:
the optional status label
See Also:
-
setValidationStatusHandler
Sets the status handler to track form status changes.
Setting this handler will override the default behavior, which is to let fields show their validation status messages and show binder level validation errors or OK status in the label set with
setStatusLabel(HasText)
.This handler cannot be set after the status label has been set with
setStatusLabel(HasText)
, orsetStatusLabel(HasText)
cannot be used after this handler has been set.Parameters:
statusHandler
- the status handler to set, notnull
Throws:
NullPointerException
- fornull
status handlerSee Also:
-
getValidationStatusHandler
Gets the status handler of this form.
If none has been set with
setValidationStatusHandler(BinderValidationStatusHandler)
, the default implementation is returned.Returns:
the status handler used, never
null
See Also:
-
getValidationErrorHandler
Gets the validation error of this form.
If none has been set with
setValidationErrorHandler(BinderValidationErrorHandler)
, the default implementation is returned.Returns:
the error handler used, never
null
See Also:
-
setValidationErrorHandler
Sets the validation error handler to update error status for fields when the user input is validated.
The error handler is invoked by methods
handleError(HasValue, ValidationResult)
andclearError(HasValue)
.DefaultBinderValidationErrorHandler
instance is used if the handler is not explicitly set.Parameters:
handler
- the status handler to set, notnull
Throws:
NullPointerException
- fornull
status handlerSee Also:
-
addStatusChangeListener
Adds status change listener to the binder.
The
Binder
status is changed whenever any of the following happens:- if it's bound and any of its bound field or select has been changed
writeBean(Object)
orwriteBeanIfValid(Object)
is calledreadBean(Object)
is calledsetBean(Object)
is calledremoveBean()
is calledBinder.BindingBuilder.bind(ValueProvider, Setter)
is calledvalidate()
orBinder.Binding.validate()
is called
Parameters:
listener
- status change listener to add, not nullReturns:
a registration for the listener
See Also:
-
addListener
Adds a listener to the binder.
Type Parameters:
T
- the event typeParameters:
eventType
- the type of the eventmethod
- the consumer method of the listenerReturns:
a registration for the listener
-
addValueChangeListener
public Registration addValueChangeListener(HasValue.ValueChangeListener<? super HasValue.ValueChangeEvent<?>> listener) Adds field value change listener to all the fields in the binder.
Added listener is notified every time after any bound field value is changed, i.e. the UI component value was changed and passed or failed any conversions and validations. If conversions and validations passed, the value in the bean will be updated before the listener is executed. The same functionality can be achieved by adding a
HasValue.ValueChangeListener
to all fields in theBinder
.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 listenerReturns:
a registration for the listener
See Also:
-
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 fieldTARGET
- the target data typeParameters:
field
- the field to bind, not nullconverter
- the converter for converting between FIELDVALUE and TARGET types, not nullhandler
- the handler to notify of status changes, not nullReturns:
the new incomplete binding
-
doCreateBinding
protected <FIELDVALUE,TARGET> Binder.BindingBuilder<BEAN,TARGET> doCreateBinding(HasValue<?, FIELDVALUE> field, Converter<FIELDVALUE, TARGET> converter, BindingValidationStatusHandler handler) -
handleError
Handles a validation error emitted when trying to write the value of the given field.
TODO:
Parameters:
field
- the field with the invalid valueresult
- the validation error result -
clearError
Clears the error condition of the given field, if any.
TODO
Parameters:
field
- the field with an invalid value -
handleValidationStatus
Default
BindingValidationStatusHandler
functional method implementation.Parameters:
status
- the validation status -
getBindings
Returns the bindings for this binder.
Returns:
a list of the bindings
-
handleBinderValidationStatus
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(HasText)
.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)
orwriteBeanIfValid(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:Return values 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
-
hasChanges
Checks whether a bound field has uncomitted changes.
Parameters:
binding
- Binding to be checkedReturns:
true if field has been changed.
-
setReadOnly
public void setReadOnly(boolean readOnly) Sets the read only state to the given value for all currently bound fields.
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 -
configureBinding
protected Binder.BindingBuilder<BEAN,?> configureBinding(Binder.BindingBuilder<BEAN, ?> binding, PropertyDefinition<BEAN, ?> definition) Configures the
binding
with the property definitiondefinition
before it's being bound.Parameters:
binding
- a binding to configuredefinition
- a property definition informationReturns:
the new configured binding
-
bindInstanceFields
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 usingBinder.BindingBuilder.bind(String)
.For example:
This binds the firstName TextField to a "firstName" property in the item, lastName TextField to a "last" property.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);
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>
andInteger
property (that would be a case of "age" property). In such case, an attempt is made to get a suitable converter from aConverterFactory
but, if there is no match, anIllegalStateException
will be thrown, unless the field has been configured manually before calling thebindInstanceFields(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 bindThrows:
IllegalStateException
- if there are incompatible HasValue<T> and property typesSee Also:
-
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. -
getBinding
Gets the binding for a property name. Bindings are available by property name if bound using
bind(HasValue, String)
,Binder.BindingBuilder.bind(String)
or indirectly usingbindInstanceFields(Object)
.Parameters:
propertyName
- the property name of the binding to getReturns:
the binding corresponding to the property name, or an empty optional if there is no binding with that property name
-
getFields
Returns the fields this binder has been bound to.
Returns:
the fields with bindings
-
removeBinding
Finds and removes all Bindings for the given field.
Parameters:
field
- the field to remove from bindings -
removeBinding
Removes the given Binding from this Binder.
Parameters:
binding
- the binding to remove -
removeBindingInternal
Removes (internally) the
Binding
from the bound properties map (if present) and from the list ofBinding
s. Note that this DOES NOT remove theValueChangeListener
that theBinding
might have registered with anyHasValue
s or decouple theBinder
from within theBinding
. To do that, useBinder.Binding.unbind()
This method should just be used for internal cleanup.Parameters:
binding
- TheBinding
to remove from the binding map -
removeBinding
Finds and removes the Binding for the given property name.
Parameters:
propertyName
- the propertyName to remove from bindings -
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. -
isValidatorsDisabled
public boolean isValidatorsDisabled()Returns if the validators including bean level validators are disabled or enabled for this Binder.
Returns:
Boolean value
-
setFieldsValidationStatusChangeListenerEnabled
public void setFieldsValidationStatusChangeListenerEnabled(boolean fieldsValidationStatusChangeListenerEnabled) Control whether bound fields implementing
HasValidator
subscribe for field'sValidationStatusChangeEvent
s and willvalidate
upon receiving them.Parameters:
fieldsValidationStatusChangeListenerEnabled
- Boolean value. -
isFieldsValidationStatusChangeListenerEnabled
public boolean isFieldsValidationStatusChangeListenerEnabled()Returns if the bound fields implementing
HasValidator
subscribe for field'sValidationStatusChangeEvent
s and willvalidate
upon receiving them.Returns:
Boolean value
-
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 usingBinder.BindingBuilder.withEqualityPredicate(SerializableBiPredicate)
.Parameters:
changeDetectionEnabled
- Boolean value -
isChangeDetectionEnabled
public boolean isChangeDetectionEnabled()Returns if change/revert detection is enabled. 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 usingBinder.BindingBuilder.withEqualityPredicate(SerializableBiPredicate)
.Returns:
Boolean value
-
setBindingExceptionHandler
Sets a
handler
to customize theRuntimeException
thrown by delegates (likeSetter
,ValueProvider
,HasValue
) used insideBinder
to be able to identify the bound field.It allows to set a custom binding exception handler in case of exception details provided be the default handler are not enough, or, in other way around, it should be reduced.
DefaultBindingExceptionHandler
instance is used if the handler is not explicitly set.Parameters:
handler
- the exception handler, notnull
See Also:
-
getBindingExceptionHandler
Gets the current exception handler.
If none has been set with
setBindingExceptionHandler(BindingExceptionHandler)
, the default implementation is returned.Returns:
the exception handler, not
null
-