【发布时间】:2016-05-11 20:43:00
【问题描述】:
我尝试在 symfony 3 中创建 custom constraint
我有错误
约束 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!!!
}
}
我的供应商/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)
{
$value->getId(); // this code not working, because $value is STRING!!
$this->context->buildViolation($constraint->message)
->atPath('code')
->addViolation();
}
}
我在哪里做错了?
【问题讨论】:
标签: php validation constraints symfony