profileRyan KesPGP keyI build stuffEmailGithubTwitterLast.fmMastodonMatrix

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 doesn’t support that feature yet