2012-10-23 72 views
3

我对Assert/Callback验证有问题。我使用this作为我的代码的示例,但Symfony只是忽略了验证功能。这是我的实体代码Symfony2实体注释未调用Assert/Callback方法

namespace Vendor\Bundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 
use Gedmo\Mapping\Annotation as Gedmo; // gedmo annotations 
use Symfony\Component\Validator\Constraints as Assert; 
use Symfony\Component\Validator\ExecutionContext; 


/** 
* @Assert\Callback(methods={"isValidFirma"}) 
* @ORM\Entity(repositoryClass="Vendor\Bundle\Entity\UserProfileRepository") 
* @ORM\Table(name="user_profile") 
*/ 
class UserProfile 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    //... 

    public function isValidFirma(ExecutionContext $context){ 
     $context->addViolationAtSubPath('Firma', 'Company name must be present', array(), null); 
     // as of sf 2.3 use addViolationAt() instead [reference: https://github.com/propelorm/PropelBundle/issues/234 ] 
    }  

    //...    

} 

isValidFirma相关部分是永远不会被调用。我尝试了validation.yml文件而不是注释,但没有成功。在每次更改之后,我清除了大约五十次的缓存,但也无济于事。可能是什么问题呢?

+0

为什么在'@Assert \ Callback'注释之前有两个星号? –

+0

这是一个错字。与实际问题无关。 – Kuro

+0

你确定它没有被叫?你是否在方法内部放置了'throw new \ Exception(...)'这样的东西来看看它是否会起作用?无论如何;你总是可以使用'@Assert \ True(message =“你的信息”)来代替,这个工作非常完美。 – Zeljko

回答

3

解决方案。问题在于使用验证器组。断言验证器必须是该组的一部分,否则它不会触发。 这片形式的类文件的代码是罪魁祸首:

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $vg = array('my-profile'); 


    $resolver->setDefaults(array(
     'validation_groups' => $vg 
    )); 
} 

改变与断言行至

* @Assert\Callback(methods={"isValidFirma"}, groups={"my-profile"}) 

的伎俩。