2014-03-26 124 views
1

在使用表单更新对象之后,对于某个字段(foo)中的某个值,我想检查是否存在具有特定属性值的持久子对象。symfony2:验证取决于查询

所以我创建了一个自定义验证器作为参数传递原则,但是..如何传递对象(或对象的id)和一定的值foo来创建查询?

这是我的代码:

class ChildCategoryHasItsOwnPageValidator extends ConstraintValidator 
{ 
    protected $doctrine; 

    public function __construct(RegistryInterface $doctrine) 
    { 
     $this->doctrine = $doctrine; 
    } 


    public function validate($value, Constraint $constraint) 
    { 
     //... 
    } 
} 

Placas\FrontendBundle\Entity\Category: 
    properties: 
     ownPage: 
      - Placas\FrontendBundle\Validator\Constraints\ChildCategoryHasItsOwnPage: ~ 

/** 
* @Annotation 
*/ 
class ChildCategoryHasItsOwnPage extends Constraint 
{ 
    public $message = 'This category has a child category with an own page. You can not define an own page for this category.'; 

    public function validatedBy() 
    { 
     return "child_category_has_its_own_page"; 
    } 
} 

Placas\FrontendBundle\Entity\Category: 
    properties: 
     ownPage: 
      - Placas\FrontendBundle\Validator\Constraints\ChildCategoryHasItsOwnPage: ~ 
+1

请用英文写的代码。 –

+0

@TomaszKowalczyk我编辑了我的问题,谢谢。 – ziiweb

+0

通过阅读UniqueEntity和UniqueEntityValidator的代码获取灵感(它在数据库中执行一些检查) – AlterPHP

回答

0

我想这会帮助你:http://symfony.com/doc/current/reference/constraints/Callback.html

它应该这样对你: (Symfony的2.4版本)

你的配置:

Placas\FrontendBundle\Entity\Category: 
    constraints: 
     - Callback: [validate] 

在你的实体:

use Symfony\Component\Validator\ExecutionContextInterface; 

class Category 
{ 
    public function validate(ExecutionContextInterface $context) 
    { 
     $children = $this->getChildren(); // assuming you have this relationship and its getter 
     foreach ($children as $child) 
     { 
      if ($child->foo != '') // or whatever test you want to make 
      { 
       $context->addViolationAt(
        'foo', 
        'This category has a child category with an own page. You can not define an own page for this category.', 
        array(), 
        null 
       ); 
      } 
     } 
    } 
}