2013-10-19 178 views
1

我正在编写一个REST API,我的问题是当我想在一个与其他实体有一对多关系的实体中反序列化请求时,因为当我想要持久化对象,而不是将现有的“孩子”放在一起,教义创建一个新的,并将他分配给对象。Synfony自定义验证器在验证中改变对象值

下面是一个职位例如:

{ “类别”:{ “ID”:1},{ “主题”:{ “ID”:1}}

我预计会发生,是添加一个新类别:1和主题:1,但相反主义创建一个新的类别/主题。

我想要做的就是改变通过自定义验证内的学说对象与JMS串行解串创建的类/主题对象,

class Channel 
{ 

    /** 
    * @ChoiceEntity(targetEntity="Bundle\ChannelBundle\Entity\ChannelCategory", allowNull=true) 
    * @Type("Bundle\ChannelBundle\Entity\ChannelCategory") 
    */ 
    public $category; 

    /** 
    * @ChoiceEntity(targetEntity="Bundle\ChannelBundle\Entity\Theme", allowNull=true) 
    * @Type("Bundle\ChannelBundle\Entity\Theme") 
    */ 
    public $theme; 
} 

这里自定义验证:

class ChoiceEntityValidator extends ConstraintValidator 
{ 
    /** 
    * 
    * @var type 
    */ 
    private $entityManager; 

    /** 
    * 
    * @param type $entityManager 
    */ 
    public function __construct($entityManager){ 
     $this->entityManager = $entityManager;  
    } 

    /** 
    * @param FormEvent $event 
    */ 
    public function validate($object, Constraint $constraint) 
    { 
     if($constraint->getAllowNull() === TRUE && $object === NULL){//null allowed, and value is null 
      return; 
     } 

     if($object === NULL || !is_object($object)) { 
      return $this->context->addViolation($constraint->message); 
     } 

     if(!$this->entityManager->getRepository($constraint->getTargetEntity())->findOneById($object->getId())) { 
      $this->context->addViolation($constraint->message); 
     }  
    } 
} 

那么有没有一种方法可以通过存储库结果中的值更改自定义验证器中的$对象?

回答

3

我不认为在自定义验证器中编辑验证的对象是个好主意。

记住您添加自定义验证应该用来检查你的对象是有效还是无效(取决于您的验证规则)。

如果要编辑对象,则应在调用验证过程之前执行该操作。您可能需要使用Data Transformers

+0

好点,我不知道数据变形金刚,这就是为什么我想这样做,但我知道这不是一个最佳实践,谢谢! –