Andrei Baidoc
Andrei Baidoc

Reputation: 85

Synfony custom validator alter object value within validation

I'm writing a REST API, my problem is when I want to deserialize an request in an entity that has a one to many relation to other entity, because when I want to persist the object instead of alocationg the existing "child", Doctrine creates a new one and alocates him to the object.

Here is an post example:

{"category": {"id": 1}, {"theme": {"id": 1} }

What I expect to happen, is to add a new channel with category:1 and theme:1, but instead doctrine creates a new category/theme.

What I wanted to do is to change the category/theme object created by deserializing with JMS Serializer in an Doctrine object within the custom validator,

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

And here the custom validator:

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

So is there a way of changing the $object from the custom validator with the value from repository result?

Upvotes: 1

Views: 149

Answers (1)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

I don't think that editing the validated object within your custom validator is a good idea.

Keep in mind that the custom validator you added should be only used to check if your object is valid or not (depending on your validation rules).

If you want to edit the object, you should then do it before invoking the validation process. You'll probably need to use Data Transformers.

Upvotes: 3

Related Questions