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 ValidationEvent 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 ValidationThe 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 theonSubmit
method to this form.- The
:state
attribute from the<b-form-input>
component displays the input in red in case of error. - The
<b-form-invalid-feedback>
component also uses the:state
attribute. It works like av-if
to display or not a list of errors related to the previous input. - The Symfony Boilerplate provides the
<ErrorsList>
component. - The
formState
method returns the current state of a given GraphQL key (see below for more details). - The
formErrors
method returns the list of errors of a given GraphQL key (see below for more details). - Both
formState
andformErrors
methods come from theForm
mixin.
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 StateMost 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.