Try   HackMD

Symfony - Validation

tags: Symfony gobelins

Initialisation

 composer require symfony/validator doctrine/annotations

Contraintes

class NotBlank extends Constraint
{
    const IS_BLANK_ERROR = 'c1051bb4-d103-4f74-8988-acbcafc7fdc3';

    protected static $errorNames = [
        self::IS_BLANK_ERROR => 'IS_BLANK_ERROR',
    ];

    public $message = 'This value should not be blank.';
    public $allowNull = false;
}

Ci-dessus un exemple de contrainte native. Il est possible de la modifier, notament pour customiser le message d'erreur de la contrainte.

Ajouter des contraintes

Annotations

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

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

class Author
{
    /**
     * @Assert\NotBlank
     */
    private $name;
}
// 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;

    // ...
}

Yaml

# config/validator/validation.yaml
App\Entity\Author:
    properties:
        name:
            - NotBlank: ~

Valider des données

// ...
use App\Entity\Author;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;

// ...
public function author(ValidatorInterface $validator)
{
    $author = new Author();
    
    $errors = $validator->validate($author);

    if (count($errors) > 0) {
        $errorsString = (string) $errors;

        return new Response($errorsString);
    }

    return new Response('The author is valid! Yes!');
}