Loading & Saving Form Data
After your bindings are set up, 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.
The benefits of configuring such a submit
behavior for the binder are:
-
The binder can track the submission progress, such as to disable a save button when a submission is ongoing.
-
Submission failures are handled automatically, so there is no need to do an explicit
try-catch
.
For example, you can define a submit
behavior to submit to an endpoint method, as follows:
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)}></TextField>
<Button onClick={submit}>Save</Button>
</section>
);
}