Symfony自定义验证器在验证中更改对象值

时间:2013-10-19 12:46:49

标签: php validation symfony doctrine-orm

我正在编写REST API,我的问题是当我想要在与其他实体具有一对多关系的实体中反序列化请求时,因为当我想要持久化对象而不是alocationg现有的“子”时“,Doctrine创造了一个新的,并将他分配给对象。

这是一个帖子示例:

  

{“category”:{“id”:1},{“theme”:{“id”:1}}

我期望发生的是添加一个新类别:1和主题:1的频道,而不是教条创建一个新的类别/主题。

我想要做的是更改通过自定义验证器中的Doctrine对象中的JMS Serializer反序列化创建的类别/主题对象,

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);
        }       
    } 
}

那么有没有办法使用存储库结果中的值更改自定义验证器中的$对象?

1 个答案:

答案 0 :(得分:3)

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

请注意您添加的自定义验证程序应用于检查对象是否有效(具体取决于您的验证规则)。

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