Docs

Documentation versions (currently viewingVaadin 24)

Loading & Saving Form Data

Loading data to Binder and submitting it for saving.

After your bindings are set, you’ll need to fill the bound UI components with data from your business objects.

Loading Data to Binder

You can use the read() method from the UseFormResult instance to read values from a business object instance into the UI components.

import { useEffect } from 'react';
import { useForm } from '@vaadin/hilla-react-form';

import { PersonEndpoint } from 'Frontend/generated/endpoints';
import PersonModel from 'Frontend/generated/com/example/application/PersonModel';

export default function PersonView() {
  const { read } = useForm(PersonModel);

  useEffect(() => {
    PersonEndpoint.loadPerson().then(read);
  }, [])

  // ...
}

Using the reset() method will reset to the previous value, which is initially empty.

import { useForm } from '@vaadin/hilla-react-form';

import PersonModel from 'Frontend/generated/com/example/application/PersonModel';

export default function PersonView() {
  const { reset } = useForm(PersonModel);

  return (
    <section>
      // other form fields ...
      <Button onClick={reset}>Reset</Button>
    </section>
  );

}

You can use the clear() method to set the form to empty.

import { useForm } from '@vaadin/hilla-react-form';

import PersonModel from 'Frontend/generated/com/example/application/PersonModel';

export default function PersonView() {
  const { clear } = useForm(PersonModel);

  return (
    <section>
      // other form fields ...
      <Button onClick={clear}>Clear</Button>
    </section>
  );

}

Saving Data

You can define a submit callback when calling useForm to configure the onSubmit behavior of the binder.

Configuring a submit behavior this way for the binder can be beneficial:

  • Binder can track the submission progress, which is useful for disabling a save button, for instance, when a submission is ongoing.

  • Submission failures are applied to the form fields, automatically. Therefore. there is no need to do an explicit try-catch.

  • Submission overall errors can be handled globally using a promise’s .catch block.

Below is an example in which submit behavior is set to submit to an endpoint method:

import { useForm } from '@vaadin/hilla-react-form';

import { PersonEndpoint } from 'Frontend/generated/endpoints';
import PersonModel from 'Frontend/generated/com/example/application/PersonModel';

export default function PersonView() {
  const { model, submit, field } = useForm(PersonModel, {
    onSubmit: async (person) => {
      await PersonEndpoint.savePerson(person);
    }
  });

  return (
    <section>
      <TextField label="Full name" {...field(model.fullName)} />
      <Button onClick={submit}>Save</Button>
    </section>
  );

}