Symfony 3.4 で独自のバリデーションルールを作っています。
データベースを検証するバリデーションなのでサービスとして作って DependencyInjection でサービスコンテナーを扱えるようにするつもりです。
一応簡単なサンプルを作って動作することは確認できたのですが使い方によってエラーが起きてしまいます。
php
1<?php 2namespace AppBundle\Validator\Constraints; 3 4use Symfony\Component\Validator\Constraint; 5 6class Example extends Constraint 7{ 8 public $message = 'this is example.'; 9 10 public function validatedBy() 11 { 12 return 'example_validator'; 13 } 14}
yaml
1 app.validator.example: 2 class: AppBundle\Validator\Constraints\ExampleValidator 3 tags: 4 - { name: validator.constraint_validator, alias: example_validator }
これは下記のような FormBuilder では正しく動作しました。
php
1 $builder 2 ->add('title', TextType::class, [ 3 'constraints' => [new MyAssert\Example()] 4 ])
しかし Validator 単体で使用すると ClassNotFoundException が発生します。
php
1 $validator = Validation::createValidator(); 2 $violations = $validator->validate('test', array( 3 new MyAssert\Example() 4 ));
エラーの内容は次のとおりです。
Attempted to load class "example_validator" from the global namespace. Did you forget a "use" statement?
おそらく validatedBy() の return 'example_validator';
の部分のことだと思うのですがどのように書き換えればいいかわかりません。
FormBuilder でも単体でも動作するようにしたいのですがなにかが足りていないのでしょうか?
追記
バリデーター自体は次のようになっています。完全に検証用なのでバリデートはできません。
class ExampleValidator extends ConstraintValidator { public function __construct(Container $container) { $this->container = $container; } public function validate($value, Constraint $constraint) { dump($this->container->get("doctrine")); exit; } }
あなたの回答
tips
プレビュー