How to validate unique entities in an entity collection in symfony2

后端 未结 4 607
心在旅途
心在旅途 2020-12-29 09:46

I have an entity with a OneToMany relation to another entity, when I persist the parent entity I want to ensure the children contain no duplicates.

Here\'s the class

4条回答
  •  执念已碎
    2020-12-29 10:26

    I can't manage to make the previous answer works on symfony 2.6. Because of the following code on l. 852 of RecursiveContextualValidator, it only goes once on the validate method when 2 items are equals.

    if ($context->isConstraintValidated($cacheKey, $constraintHash)) {
        continue; 
    } 
    

    So, here is what I've done to deals with the original issue :

    On the Entity :

    * @AcmeAssert\UniqueInCollection(propertyPath ="product")
    

    Instead of

    * @Assert\All(constraints={
    *     @AcmeAssert\UniqueInCollection(propertyPath ="product")
    * })
    

    On the validator :

    public function validate($collection, Constraint $constraint){
    
        $propertyAccessor = PropertyAccess::getPropertyAccessor(); 
    
        $previousValues = array();
        foreach($collection as $collectionItem){
            $value = $propertyAccessor->getValue($collectionItem, $constraint->propertyPath);
            $previousSimilarValuesNumber = count(array_keys($previousValues,$value));
            if($previousSimilarValuesNumber == 1){
                $this->context->addViolation($constraint->message, array('%email%' => $value));
            }
            $previousValues[] = $value;
        }
    
    }
    

    Instead of :

    public function isValid($value, Constraint $constraint)
    {
        $valid = true;
    
        if($constraint->propertyPath){
            $propertyAccessor = PropertyAccess::getPropertyAccessor(); 
            $value = $propertyAccessor->getValue($value, $constraint->propertyPath);
        }
    
        if(in_array($value, $this->collectionValues)){
            $valid = false;
            $this->setMessage($constraint->message, array('%string%' => $value));
        }
    
        $this->collectionValues[] = $value;
    
        return $valid
    
    }
    

提交回复
热议问题