PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 31, 2022

[FIXED] Do you have to register your custom validators in symfony

 January 31, 2022     customvalidator, doctrine, php, symfony, validation     No comments   

Issue

I was reading the documentation on making custom validators and it doesn't state that you have to register custom created validators, but what else would cause this issue?

I created a custom constraint:

namespace Lib\Validators\UniqueValidator\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class Email extends Constraint {

  public $message = "The email entered already exists.";
}

and a custom validator:

namespace Lib\Validators\UniqueValidator;

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

class EmailValidator extends ConstraintValidator {

  public function validate($value, Constraint $constraint) {
    var_dump($value, $constraint); exit;
  }
}

and then when I go to use it:

The annotation "@\Lib\Validators\UniqueValidator\Constraint\Email" in property  > ImageUploader\Models\User::$email does not exist, or could not be auto-loaded.

And I am not sure why. Is there a spelling mistake I can't see? I checked everything 50 times.

In my bootstrap.php I have:

$loader = require 'vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

But those are for the symfony validators, do I have to do something similar for my custom ones? I should also mention I am using the symfony validators component and not full stack symfony.

For the view of the directory structure I have done:

enter image description here

\Lib points to the base of lib/. I'm sure this isn't standard and it will be fixed soon.


Solution

Your custom validator must be in the same folder than your constraint. According to your namespaces, it's not the case.

If you want to separate them, you can override the validatedBy() method of your Constraint class :

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


Answered By - Raphaël Malié
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing