2016-06-30 66 views
0

我的表單與建立約束的模型綁定在一起。當值符合約束時驗證通過,反之亦然...
除了只有一個字段裝飾有似乎永遠不會被評估的表達式約束。Symfony 3驗證表達式未評估

我需要的是:如果我的模型「helpType」屬性值是不包含在某些陣列不及格驗證所以我希望下面的代碼工作:

// PostModel.php

/** 
* @Assert\Expression(
*  "this.isValidHelpType()", 
*  message="post.create.help-invalid" 
*) 
* @ORM\Column(type="integer") 
*/ 
protected $helpType; 
public function isValidHelpType() 
{ 
    return in_array($this->getHelpType(), Post::getHelpTypes()); 
} 

// PostType.php

// … 
->add('helpType', TextType::class, [ 'error_bubbling' => true, 'label'=>false ]) 
// … 

約束似乎從來沒有得到執行,因爲無論何時我把"false"代替表達式,或從內部die; isValidHelpType()函數(在return語句之前,顯然)沒有任何反應。

是否存在某種不同類型的約束,如class級別與property級別的異或行爲?無論如何,這裏有什麼想法?
謝謝。

回答

0

實際上,我使用的是驗證組,我只是忘了將group={"some_group"}屬性放在該約束上,與執行上下文相關。

最後,這裏是我結束了在爲了確保一(整數)值包含在一些陣列:

<?php 
// ... 
/** 
* @Assert\Expression(
*  "this.isHelpTypeValid()", 
*  message="create.help-invalid", 
*  groups={"creation"} 
*) 
* @ ORM\Column(type="integer") 
*/ 
protected $helpType; 
public function isHelpTypeValid() 
{ 
    // value from POST are strings, now make sure it looks like numeric 
    return is_numeric($this->getHelpType()) 
     // Cast to integer and set value 
     && $this->setHelpType((int)$this->getHelpType()) 
     // now test if reference array contains that value 
     && in_array($this->getHelpType(), Post::getHelpTypes(), true); 
}