0

我创建了自定义验证器来验证对象比较其字段(它使用 EntityManager 来验证字段)。当对象无效时,MyValidator 将错误消息添加到 Form 对象,因为验证器关联到实体而不是字段。

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

验证失败时,有没有办法添加字段错误而不是表单错误?

4

1 回答 1

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);
       }
   }


}
于 2012-10-12T07:54:46.853 回答