I just noticed in my symfony project that if I have an entity that has a non-nullable field, and that in the formType I make sure that the field is required.
So in the rendering of the page, if I do "inspect the element" and I manually remove the "required" attribute from the field, well I can validate, and in this case I will have a doctrinal error instead of staying on the form page with a simple validation error
SQLSTATE[23000]: Integrity constraint violation: 1048 Le champ 'titre' ne peut être vide (null)
However, I use {{form_row(form.field)}}
in my Twig file, so I should have the form_error too.
Does this mean that for all my entities, I have to add @Assert\NotNull
each time to avoid this problem? It seems far-fetched even if it is not managed automatically
Using the @Assert\NotNull
annotations is indeed the proper way to go if you want server-side validation.
Alternatively, you can add the constraint in the form type if you don't want to touch your entities:
'required' => true,
'constraints' => new Assert\NotNull(),
Now, if you really want auto-mapping of doctrine types into Symfony validation, read the following article: https://symfony.com/blog/new-in-symfony-4-3-automatic-validation
There are some issues with that feature which made the Symfony team disable it by default. Solution is to uncomment the following lines in config/packages/validator.yaml
:
#auto_mapping:
# App\Entity\: []
Symfony 4.4 also ships with two new annotations (@Assert\EnableAutoMapping
and @Assert\DisableAutoMapping
) which allow you to enable/disable that feature on per-class/field basis