2014-03-26 123 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 
       ); 
      } 
     } 
    } 
}