Forms
In the previous chapters, we saw how to centralize the validation in the API. The next step is to integrate this validation mechanism with the web application.
Let's see how to do that! 😊
note
📣  The Symfony Boilerplate uses BootstrapVue as templating framework. However, most of the explanations from this chapter should work with most frameworks with little adjustments.
Browser Validation#
Event if most of the validation occurs in the API, there are some rules that are better to validate directly in the browser.
For instance:
Here there are three rules:
- The browser focuses this input first (UI logic).
- The browser trims the input's content.
- The browser does not allow to submit the form until this input has content.
Most of the time, that's all you have to do on the browser side.
API Validation#
The Symfony Boilerplate provides the Form mixin. This mixin brings everything you need for integrating
the API validation in your UI.
note
📣  A mixin content merges with the content of your Vue component.
Most of the logic occurs in the onSubmit method from your component:
note
📣  If the error response is not about validation (i.e., 400 HTTP code), the hydrateFromErrors method
throws the error back. The src/webapp/layouts/error.vue component will then catch it.
Now, we have to display the validation errors to the user. Thanks to BootstrapVue and
the Form mixin, it can be done quite easily:
<b-form @submit.stop.prevent="onSubmit">binds theonSubmitmethod to this form.- The
:stateattribute from the<b-form-input>component displays the input in red in case of error. - The
<b-form-invalid-feedback>component also uses the:stateattribute. It works like av-ifto display or not a list of errors related to the previous input. - The Symfony Boilerplate provides the
<ErrorsList>component. - The
formStatemethod returns the current state of a given GraphQL key (see below for more details). - The
formErrorsmethod returns the list of errors of a given GraphQL key (see below for more details). - Both
formStateandformErrorsmethods come from theFormmixin.
A GraphQL key is either:
- The GraphQL field name if
InvalidModel. - The upload's directory name if
InvalidStorable. - The PHP argument name if it's a GraphQLite annotation.
Loading State#
Most of the time, you want to display a loader or make your form read-only when the user is submitting the form.
The Symfony Boilerplate provides the GlobalOverlay mixin for that task:
note
📣  All layouts from the Symfony Boilerplate works with this mixin. If you add a custom layout, make sure
it integrates well with the GlobalOverlay mixin.