shaax
shaax

Reputation: 336

Display constraint validator error messages in Symfony

I don't know how to display my Constraint Validator error messages.

Errors are correctly detected, because if I put a null or negative value in my form, the word "Error" (see on twig file) is displayed, but not the error message of my validator.

No, I don't want to manage my error messages directly on my validation.yaml.

No, I don't want to manage my error messages directly on my Form.

I need to do this properly in my Validation folder because I will have a lot of them.

src/Validator/Constraints/Type.php :

<?php

namespace App\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class Type extends Constraint
{

    public $numericPositiveNotNull = "Merci de renseigner une valeur numérique, positive et non nulle";

    public function validatedBy()
    {
        return \get_class($this).'Validator';
    }
}

src/Validator/Constraints/TypeValidator.php

<?php

namespace App\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;


class TypeValidator extends ConstraintValidator
{

    public function validate($value, Constraint $constraint)
    {
        if (!is_int($value)) {
            $this->context->buildViolation($constraint->numericPositiveNotNull)
                ->addViolation();
        }
    }
}

validator/validation.yaml

App\Entity\Donation:
    properties:
      weight:
        - App\Validator\Constraints\Type: ~

DonationController.php

[...]
        return $this->render('/donation/donationFormCreate.html.twig', [
            'form' => $form->createView(),
            'formHasErrors' => $form->isSubmitted() && !$form->isValid(),
        ]);

donationFormCreate.html.twig

        {% if formHasErrors %}
             Erreur
            {{ form_errors(form) }}
        {% endif %}
[...]

Upvotes: 1

Views: 4457

Answers (1)

mkilmanas
mkilmanas

Reputation: 3485

You are not receiving any error message there, because you are displaying only the 'global' errors that apply to the whole form / validated class.

Your custom validator is however attached to a specific property, so when that validation fails, your message will also be attached to the property. I.e. to see your error message you would have to call

{{ form_errors(form.weight) }}

And that is intended to be used next to a specific form field rather than the whole form.

See https://symfony.com/doc/current/form/form_customization.html#form-errors-form-view for reference

Upvotes: 1

Related Questions