有没有办法在Symfony2中与类关联的自定义验证器中添加字段错误而不是表单错误?

时间:2012-10-11 11:57:03

标签: symfony

我创建了自定义验证器,用于验证对象的字段比较(它使用EntityManager验证字段)。 当对象无效时,MyValidator会向Form对象添加错误消息,因为验证器与Entity而非Field相关联。

/**
 * @StrictAssert\MyValidator
 */
class State extends MyEntity
{
...
}

验证失败时,有没有办法添加Field错误而不是Form错误?

1 个答案:

答案 0 :(得分:1)

在您的验证器中,您必须指定违规的字段!

使用$ context-> setPropertyPath($ propertyPath;

以下是字段长度检查的简单示例

/**
 * @Assert\Callback(methods={"MyValidator"})
 */
class MyEntity
{

   public function MyValidator(ExecutionContext $context)
   {

    $propertyPath = $context->getPropertyPath() . '.length';

        //add some logic
       if($this->getLength()>255){
           //set the pointer on the field in error
           $context->setPropertyPath($propertyPath);

           //generate the error
           $context->addViolation('Incorrect length for type', array(), null);
       }
   }


}