title: How to validate unique entities in an entity collection in symfony2
body: <p>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.</p>
  
  <p>Here's the classes I have been using, the <em>discounts</em> collection should not contain two products with the same name for a given client.</p>
  
  <p>I have a Client entity with a collection of discounts:</p>
  
  <pre><code>/**
   * @ORM\Entity
   */
  class Client {
  
      /**
       * @ORM\Id
       * @ORM\Column(type="integer")
       * @ORM\GeneratedValue(strategy="AUTO")
       */
      protected $id;
  
      /**
       * @ORM\Column(type="string", length=128, nullable="true")
       */
      protected $name;
  
      /**
       * @ORM\OneToMany(targetEntity="Discount", mappedBy="client", cascade={"persist"}, orphanRemoval="true")
       */
      protected $discounts;
  
  }
  
  /**
   * @ORM\Entity
   * @UniqueEntity(fields={"product", "client"}, message="You can't create two discounts for the same product")
   */
      class Discount {
          /**
           * @ORM\Id
           * @ORM\Column(type="string", length=128, nullable="true")
           */
          protected $product;
  
          /**
           * @ORM\Id
           * @ORM\ManyToOne(targetEntity="Client", inversedBy="discounts")
           * @ORM\JoinColumn(name="client_id", referencedColumnName="id")
           */
          protected $client;
  
          /**
           * @ORM\Column(type="decimal", scale=2)
           */
          protected $percent;
      }
  </code></pre>
  
  <p>I tried using <a href="http://symfony.com/doc/current/reference/constraints/UniqueEntity.html" rel="noreferrer">UniqueEntity</a> for the Discount class as you can see, the problem is that it seems the validator only checks what's loaded on the database (which is empty), so when the entities are persisted I get a "SQLSTATE[23000]: Integrity constraint violation".</p>
  
  <p>I have checked the <a href="http://symfony.com/doc/current/reference/constraints/Collection.html" rel="noreferrer">Collection</a> constraint buy it seems to handle only collections of fields, not entities.</p>
  
  <p>There's also the <a href="http://symfony.com/doc/current/reference/constraints/All.html" rel="noreferrer">All</a> validator, which lets you define constraints to be applied for each entity, but not to the collection as a whole.</p>
  
  <p>I need to know if there are entity collection constraints as a whole before persisting to the database, other than writing a <a href="http://symfony.com/doc/current/cookbook/validation/custom_constraint.html" rel="noreferrer">custom validator</a> or writing a <a href="http://symfony.com/doc/current/reference/constraints/Callback.html" rel="noreferrer">Callback</a> validator each time.</p>