Traverse
Edit this pageWarning: You are browsing the documentation for Symfony 4.2, which is no longer maintained.
Read the updated version of this page for Symfony 6.3 (the current stable version).
Traverse
Objects do not validate nested objects by default unless explicitly using this constraint. If only specific nested objects should be validated by cascade, consider using the Valid instead.
Basic Usage
In the following example, create three classes Book
, Author
and
Editor
that all have constraints on their properties. Furthermore,
Book
stores an Author
and an Editor
instance that must be
valid too. Instead of adding the Valid
constraint to both fields,
configure the Traverse
constraint on the Book
class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// src/Entity/Book.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @Assert\Traverse
*/
class Book
{
/**
* @var Author
*
* @ORM\ManyToOne(targetEntity="App\Entity\Author")
*/
protected $author;
/**
* @var Editor
*
* @ORM\ManyToOne(targetEntity="App\Entity\Editor")
*/
protected $editor;
// ...
}
1 2 3 4
# config/validator/validation.yaml
App\Entity\Book:
constraints:
- Symfony\Component\Validator\Constraints\Traverse: ~
1 2 3 4 5 6 7 8 9 10
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="App\Entity\Book">
<constraint name="Symfony\Component\Validator\Constraints\Traverse"/>
</class>
</constraint-mapping>
1 2 3 4 5 6 7 8 9 10 11 12 13
// src/Entity/Book.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
class Book
{
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addConstraint(new Assert\Traverse());
}
}
Options
payload
type: mixed
default: null
This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.
For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.