Skip to content

Commit b9477a7

Browse files
committed
minor #10331 (Proposal) Added a note on forms validation (mickaelandrieu, javiereguiluz)
This PR was submitted for the 4.1 branch but it was merged into the 2.8 branch instead (closes #10331). Discussion ---------- (Proposal) Added a note on forms validation Hello! regarding the way I validate my forms, I've always found that storing validation rules into my entities is a better idea than using the constraints inside my form types. When I need a really specific control on my form validation, I inject validation groups: do you think it can be viewed as a best practice? Commits ------- 68a7931 Reword 21c4c9f Added a note on forms validation
2 parents 70d6ce0 + 68a7931 commit b9477a7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

best_practices/forms.rst

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,34 @@ view layer:
145145
class="btn btn-default pull-right" />
146146
{{ form_end(form) }}
147147

148+
Validation
149+
----------
150+
151+
The `constraints`_ option allows you to attach `validation constraints`_ to any
152+
form field. However, doing that prevents the validation from being reused in
153+
other forms or other places where the mapped object is used.
154+
155+
.. best-practice::
156+
157+
Do not define your validation constraints in the form but on the object the
158+
form is mapped to.
159+
160+
For example, to validate that the title of the post edited with a form is not
161+
blank, add the following in the ``Post`` object::
162+
163+
// src/Entity/Post.php
164+
165+
// ...
166+
use Symfony\Component\Validator\Constraints as Assert;
167+
168+
class Post
169+
{
170+
/**
171+
* @Assert\NotBlank()
172+
*/
173+
public $title;
174+
}
175+
148176
Rendering the Form
149177
------------------
150178

@@ -207,3 +235,6 @@ like the form is *always* processed (even on the GET request).
207235
----
208236

209237
Next: :doc:`/best_practices/i18n`
238+
239+
.. _`constraints`: https://symfony.com/doc/current/reference/forms/types/form.html#constraints
240+
.. _`validation constraints`: https://symfony.com/doc/current/reference/constraints.html

0 commit comments

Comments
 (0)