wiki/content/20201117112727-define_constraints_as_attributes.md

1.2 KiB
Raw Blame History

date id title
2020-11-17 b632a78b-9e93-4b56-8cfe-daa3e4db12a2 Define Constraints as Attributes

Syntax

Annotations

// src/Entity/Author.php
namespace App\Entity;

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

class Author
{
    /**
     * @Assert\Choice(
     *     choices = { "fiction", "non-fiction" },
     *     message = "Choose a valid genre."
     * )
     */
    private $genre;

    // ...
}

Attributes

// src/Entity/Author.php
namespace App\Entity;

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

class Author
{
    #[Assert\Choice(
        choices: ['fiction', 'non-fiction'],
        message: 'Choose a valid genre.',
    )]
    private $genre;

    // ...
}

Caveats

The following composite constraints can't be used with attributes:

The reason is that they would require nested attributes and PHP doesnt support that feature yet