Custom constraint not show message

571 views Asked by At

in this thread im fight with a custom validator. Thanks an stackoverflow user i can do work the validator. Now, i cant do that show the error. The validator class is:

class ExistEmailValidator extends ConstraintValidator
{

    protected $userService;

    public function setUserService($us) {
        $this->userService = $us;
    }

    public function validate($value, Constraint $constraint)
    {
        if($this->userService->existUserEmail($value) == false){
            $this->context->addViolation($constraint->message, array('%string%' => $value));
        }

    }

    public function getTargets(){
        return self::CLASS_CONSTRAINT;
    }

}

And in twig i write form_errors(myForm), but the error not shows. The validator works fine, but not set the error.

Any ideas ?

1

There are 1 answers

0
Johnny On

See the Class Constraint documentation. Class contraints are passed an object not a simple value. Have you set the correct annotation on your entity? For example,

use My\Namespace\Validator\Constraints as MyAssertions;

/**
 * @MyAssertions\ExistEmailValidator
 *
 */
class MyEntity
{
    protected $id;

    protected $email;

    // etc...

}

In your validator, you will receive an instance of MyEntity from which you can retrieve the email value and validate it. As mentioned in a comment above, you probably want to use addViolationAt as well.

I hope that helps and that I'm understanding your situation correctly. I'm sure there are better explanations out there though.