Docs

Hilla is now an integrated part of Vaadin 24 – AnnouncementHilla Documentation

Binding Data to Input Fields

Implementing data binding, type mapping and error messages when binding data with Hilla components.

Client Form binder supports out of the box the set of form elements present in Hilla components. This means that data binding, type mapping, required flag, and validation messages will function without any extra work.

Configuring Server Data & Endpoint

When defining Bean objects in Java, apart from the type, you can define validation and error messages.

For this article, the code on the client side is based on the data and endpoints defined in the following Java classes:

public class MyEntity {
    @AssertTrue(message = "Please agree this")
    Boolean myBooleanField = false;

    @NotEmpty(message = "Select at least one option")
    List<String> myListField = Arrays.asList("item-1");

    @Pattern(regexp = "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,}",
                message = "must be 8+ characters, with uppercase, lowercase, and numbers")
    String myPasswordField = "bar";

    @Email(message = "must be a valid email address")
    String myEmailField = "foo@bar.baz";

    @PositiveOrZero(message = "Should be positive or zero")
    Integer myIntegerField = 12;
    @Positive(message = "Should be positive")
    Double myDoubleField = 12.33d;

    @Future(message = "Should be a date in the future")
    LocalDate myDateField = LocalDate.now().plusDays(1);
    LocalDateTime myDateTimeField = LocalDateTime.now();
    LocalTime myTimeField = LocalTime.now();

    @Min(0) @Max(1)
    Integer mySelectField = 1;
}

@Endpoint
public class MyEndpoint {
    public MyEntity getMyEntity() {
        return new MyEntity();
    }

    public List<String> getMyOptions() {
        return Arrays.asList("item-1", "item-2", "item-3");
    }
}

Configuring Client Fields

Before using form binders, you need to import your entity models and instantiate the binder. You also need to perform the endpoint call to get the entity value, as explained in the tutorials Binding Data to Forms and Loading from and Saving to Business Objects.

For this article, these are the significant lines needed in the view:

import { MyEndpoint } from 'Frontend/generated/MyEndpoint';
import MyEntityModel from 'Frontend/generated/com/example/MyEntityModel';
...
const form = useForm(MyEntityModel);
...
useEffect(() => {
  MyEndpoint.getMyEntity().then(form.read);
}, []);

Binding Data to Text & Number Fields

No extra action is needed to configure the Vaadin components that represent Text & Number values.

import {TextField} from "@hilla/react-components/TextField.js";
import {PasswordField} from "@hilla/react-components/PasswordField.js";
import {IntegerField} from "@hilla/react-components/IntegerField";
import {NumberField} from "@hilla/react-components/NumberField.js";
import {EmailField} from "@hilla/react-components/EmailField.js";
import {TextArea} from "@hilla/react-components/TextArea.js";

...
const { model, field } = useForm(MyEntityModel);
...
return (
  <>
    <TextField label="string"
        {...field(model.myTextField)}>
    </TextField>
    <PasswordField label="password"
        {...field(model.myPasswordField)}>
    </PasswordField>
    <IntegerField label="integer"
        {...field(model.myIntegerField)}
        stepButtonsVisible>
    </IntegerField>
    <NumberField label="number"
        {...field(model.myDoubleField)}
        stepButtonsVisible>
    </NumberField>
    <EmailField label="email"
        {...field(model.myEmailField)}>
    </EmailField>
    <TextArea label="textarea"
        {...field(model.myTextField)}>
    </TextArea>
  </>
);

Binding Data to Boolean Fields

In Hilla, three components are available for handling booleans: Checkbox, RadioButton, and Select.

Checkbox and RadioButton work fine with form binders, but neither of them has validation and failure styling. Hence, you need to do some extra work to give error feedback. In the following snippet, the background color is changed on validation error.

vaadin-checkbox[invalid], vaadin-radio-button[invalid] {
  background: var(--lumo-error-color-10pct);
}
import {Checkbox} from "@hilla/react-components/Checkbox.js";
import {RadioButton} from "@hilla/react-components/RadioButton.js";

import './my-styles.module.css';
...
const { model, field } = useForm(MyEntityModel);
...
return (
  <>
    <Checkbox label="checkbox"
        {...field(model.myBooleanField)}>
    </Checkbox>
    <RadioButton label="radio-button"
        {...field(model.myBooleanField)}>
    </RadioButton>
  </>
);

Select can be bound to a boolean, as in the following snippet:

import {Select} from "@hilla/react-components/Select.js";
...
const { model, field } = useForm(MyEntityModel);
const selectItems = [{label: "True", value: "true"}, {label: "False", value: "false"}];
...
return (
  <Select label="select"
          {...field(model.myBooleanField)}
          items={selectItems}>
  </Select>
);

Binding Data to List Fields

Hilla has several components for selection based on option lists, each one covering a specific purpose, Hence, there are various ways to set their values and options.

Configuring the Options for Selection

Options for these components can be set by calling a server-side service that provides the list of strings. Since the call to the endpoint is asynchronous, one easy way is to use the Typescript map on the list received from the endpoints.

As reference, the following snippet demonstrates how to repeat a pattern, given an asynchronous method that returns a list of items. The same pattern will be used in the code blocks for each component that follow.

const [options, setOptions] = useState(Array<Entity>());
...
// using effects to execute only once
useEffect(() => {
  MyEndpoint.getMyOptions().then(entities => setOptions(options))
}, []);
...
return (
  <>
    {options.map(opt => (
      <div>{JSON.stringify(opt)}</div>
    ))}
  </>
)

Single Selection Using Item Value

For a single selection, you should use ComboBox, RadioGroup or ListBox. They can all take the selected item value as a string.

import {ComboBox} from "@hilla/react-components/ComboBox.js";
import {useEffect} from "react";
import {RadioGroup} from "@hilla/react-components/RadioGroup.js";
import {RadioButton} from "@hilla/react-components/RadioButton.js";
import {ListBox} from "@hilla/react-components/ListBox.js";
import {Item} from "@hilla/react-components/Item.js";
...
const { model, field } = useForm(MyEntityModel);
const [myOptions, setMyOptions] = useState(Array<MyEntity>());
...
useEffect(() => {
  MyEndpoint.getMyOptions().then(myEntities => setMyOptions(myEntities));
}, []);
...
return (
  <>
    <ComboBox label="combo-box"
        {...field(model.mySingleSelectionField)}
        items={myOptions}>
    </ComboBox>
    <RadioGroup label="radio-group"
                {...field(model.mySingleSelectionField)}>
      {myOptions.map(option => (
         <RadioButton value={option}
                      label={option}>
         </RadioButton>
      ))}
    </RadioGroup>
    <ListBox label="list-box"
             {...field(model.mySingleSelectionField)}>
      {myOptions.map(option => (
         <Item value={option}
               label={option}>
         </Item>
      ))}
    </ListBox>
  </>
);

Single Selection Using Index

To select items by index, you should use the Select component. This accepts an integer for the index value. Because this component is configurable via the template tag, it’s not possible to set the options with an asynchronous call.

import {useEffect} from "react";
import {Select} from "@hilla/react-components/Select.js";
...
const { model, field } = useForm(MyEntityModel);
const [myOptions, setMyOptions] = useState(Array<MyEntity>());
...
useEffect(() => {
  MyEndpoint.getMyOptions().then(myEntities => setMyOptions(myEntities));
}, []);
...
return (
  <Select label="select"
          {...field(model.mySelectField)}>
     {myOptions.map(option => (
        <Item value={option}
              label={option}>
        </Item>
     ))}
  </Select>
);

Multiple Selection

The Vaadin components for multiple selection are CheckboxGroup and MultiSelectComboBox. Both of them accept an array of strings.

import {CheckboxGroup} from "@hilla/react-components/CheckboxGroup.js";
import {Checkbox} from "@hilla/react-components/Checkbox.js";
import {MultiSelectComboBox} from "@hilla/react-components/MultiSelectComboBox.js";
...
const { model, field } = useForm(MyEntityModel);
const [myOptions, setMyOptions] = useState(Array<MyEntity>());
...
useEffect(() => {
  MyEndpoint.getMyOptions().then(myEntities => setMyOptions(myEntities));
}, []);
...
return (
  <>
    <CheckboxGroup label="check-group"
                   {...field(model.myListField)}>
      {myOptions.map(option => (
           <Checkbox value={option}
                 label={option}>
           </Checkbox>
        ))}
    </CheckboxGroup>
    <MultiSelectComboBox label=""
                         items={myOptions}>
    </MultiSelectComboBox>
  </>
);

Binding Data to Date & Time Fields

Use DatePicker to bind to Java LocalDate, TimePicker for LocalTime, and vaadin-date-time-picker for LocalDateTime.

import { DatePicker } from "@hilla/react-components/DatePicker.js";
import { TimePicker } from "@hilla/react-components/TimePicker.js";
import {DateTimePicker} from "@hilla/react-components/DateTimePicker.js";
...
return (
  <>
    <DatePicker label="date"
                {...field(model.mySelectField)}>
    </DatePicker>
    <TimePicker label="time"
                {...field(model.mySelectField)}>
    </TimePicker>
    <DateTimePicker label="date-time"
                    {...field(model.mySelectField)}>
    </DateTimePicker>
  </>
);

Wrapping Components in Custom Fields

Hilla provides the CustomField, which can be used to wrap one or multiple Vaadin fields. This works with the following components:

  • TexField

  • NumberField

  • PasswordField

  • TextArea

  • Select

  • ComboBox

  • DatePicker

  • TimePicker

import {CustomField} from "@hilla/react-components/CustomField.js";
import {TextField} from "@hilla/react-components/TextField.js";

...
return (
  <CustomField {...field(model.myTextField)}>
    <TextField label="custom-field">
    </TextField>
  </CustomField>
);
Note
There are limitations when using vaadin-custom-field with other elements previously listed:
  • the value of the custom field should be provided as a string;

  • children should have the value property in their API.