Vaadin 8 in Kotlin: Binding data
Binding from data bean to UI components is very common Vaadin feature. Vaadin 8 changes the API slightly and simplifies this operation.
Each item below references code comment number in code snippet below.
-
BeanBinder — bean binder is object that holds the state and organize validation and data conversions.
-
Binding fields — each field can be bound individually. We do binding from Vaadin UI component (e.g. TextField). Binding includes validators and possible data convertors.
-
Binding all fields — besides individual bean bindings we can bind entire bean to UI components with binder.bindInstanceFields(this) . We can even combine individual field bindings with validator definitions and then we bind rest of the bean fields that don’t require any special handling.
-
Reading value from bean — binder.readBean(task) reads value from field and store it to UI components based on binding definitions …
-
Writing values back to bean — binder.writeBean(task) writes values entered to UI components back to data bean.
-
Data class for your task object. Kotlin allows very nice and compact syntax for data beans.
// #1
var binder = BeanBinder(Task::class.java)
var task: Task
// #2
binder.forField(subject).withValidator(StringLengthValidator(
"Subject is required",3,60)
).bind("subject");
binder.forField(type).asRequired("Type is required")
.bind("type");
// #3
binder.bindInstanceFields(this)
// #4
binder.readBean(task)
// #5
binder.writeBean(task)
// #6
data class Task(var subject: String, var description: String, var type:String, var dueDate: LocalDate)
There are many options available for data binding in Vaadin 8 documentation here.