我尝试在symfony 3中创建自定义约束
我有错误
约束App\Bundle\MyBundle\Validator\Constraints\Code不能放在属性或getter上
<?php
// vendor/app/mybundle/Validator/Constraints/Code.php
namespace App\Bundle\MyBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
class Code extends Constraint
{
public $message = 'Error validate message!!!';
public function validatedBy()
{
return 'alias_name';
}
public function getTargets()
{
//return self::CLASS_CONSTRAINT; // error "The constraint cannot be put on properties or getters"
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT); // working, but $value is a STRING!!!
}
}
Run Code Online (Sandbox Code Playgroud)
我的vendor/app/mybundle/Validator/Constraints/CodeValidator.php
<?php
// vendor/app/mybundle/Validator/Constraints/CodeValidator.php
namespace App\Bundle\MyBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class CodeValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint) …Run Code Online (Sandbox Code Playgroud) 我有这个错误。请帮助。
我使用这个指令http://symfony.com/doc/current/reference/constraints/Callback.html 3.0版本(我使用Symfony 3.0)
我的验证.yml
App\Bundle\NameBundle\Entity\Product:
constraints:
- Callback: [validate]
Run Code Online (Sandbox Code Playgroud)
实体
namespace App\Bundle\NameBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Product
*/
class Product
{
/**
* @var integer
*/
private $id;
/* ... some code .... */
public function validate(ExecutionContextInterface $context)
{
$context->buildViolation('This name sounds totally fake!')
->atPath('firstName')
->addViolation();
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
解决方案:
在validation.yml中
...
- Callback: validate
...
Run Code Online (Sandbox Code Playgroud)