Skip to content

(Proposal) Added a note on forms validation #10331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions best_practices/forms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,34 @@ view layer:
<input type="submit" class="btn" value="Create" />
{{ form_end(form) }}

Validation
----------

The `constraints`_ option allows you to attach `validation constraints`_ to any
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should use the doc or ref role here instead

form field. However, doing that prevents the validation from being reused in
other forms or other places where the mapped object is used.

.. best-practice::

Do not define your validation constraints in the form but on the object the
form is mapped to.

For example, to validate that the title of the post edited with a form is not
blank, add the following in the ``Post`` object::

// src/Entity/Post.php

// ...
use Symfony\Component\Validator\Constraints as Assert;

class Post
{
/**
* @Assert\NotBlank()
*/
public $title;
}

Rendering the Form
------------------

Expand Down Expand Up @@ -190,3 +218,6 @@ submit. Both those actions will be almost identical. So it's much simpler to let
``new()`` handle everything.

Next: :doc:`/best_practices/i18n`

.. _`constraints`: https://symfony.com/doc/current/reference/forms/types/form.html#constraints
.. _`validation constraints`: https://symfony.com/doc/current/reference/constraints.html