Validation manuelle d'un objet avec le composant de validation Symfony

Publié le 09/08/2023 • Actualisé le 09/08/2023


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans un bout de code précédent, nous avons vu comment valider un tableau avec le service de validation existant de Symfony. Dans ce bout de code, nous créons manuellement un validateur, puis, nous validons un objet contenant des attributs d'assertions comme #[Assert\NotBlank].


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Samples\ProductSample;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validation;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 */
trait Snippet267Trait
{
    public function snippet267(): void
    {
        $validator = Validation::createValidatorBuilder()
            ->enableAttributeMapping()
            ->getValidator();
        $product = new ProductSample();
        /** @var ConstraintViolation $violations */
        $violations = $validator->validate($product);
        echo 'Violations: '.PHP_EOL.$violations;

        // That's it! 😁
    }
}

 Exécuter le snippet  Plus sur Stackoverflow  Plus sur le web  Snippet aléatoire

  Travaillez avec moi !