1

I have the following validations defined for ProductType, ProductTypeAttributes (OneToMany):

Bike\ProductBundle\Entity\ProductType:
    properties:
        name:
            - NotBlank: ~
        productTypeAttributes:
            - Valid: ~
Bike\ProductBundle\Entity\ProductTypeAttribute:
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
            fields: [attribute, productType]
            errorPath: attribute
            message: 'Attributes must be different for the same product type.'

There is a unique key for ProductTypeAttributes: attribute,productType.

I am using embedded forms (collection type) for ProductTypeAttributes with the possibility to add/remove items. The validation seems to work only for the already existent records in the db, happening only if I am adding a new related entity which will trigger the unique key violation for a record.

The problem is the validation doesn't work when adding two completely new related entities, with the same attribute/productType. In this case I get the "duplicate entry" exception.

So the validation checks only through db records using default findBy method, but not against newly added records themselves for duplicates.

Any way to overcome this?

StuartLC
  • 104,537
  • 17
  • 209
  • 285
gus
  • 15
  • 3

1 Answers1

0

Yes, but not through the default UniqueEntity validator. You'll have to manually create a second validator that works on the entire ProductType entity and validates that none of the new (unsaved) Attributes are the same.

Check out Symfony´s cookbook on how to make your own validator: http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

Erik
  • 1,057
  • 7
  • 11
  • I thought about creating a custom validation, where I can look for duplicates, but shouldn't doctrine know to handle this within the transaction (where multiple insertions are done)? – gus Oct 23 '14 at 12:23