title: Unique Constraints in Doctrine 2, Symfony 2
body: <p>I want to make a unique constraint in my Doctrine 2 entity such that <code>name</code> &amp; <code>test</code> are unique column wise. Meaning </p>
  
  <ul>
  <li><p>obj1</p>
  
  <ul>
  <li>name: name1</li>
  <li>test: test</li>
  </ul></li>
  <li><p>obj2</p>
  
  <ul>
  <li>name: name2</li>
  <li>test: test &lt;---- duplicated</li>
  </ul></li>
  </ul>
  
  <p>This should trigger an error as test is duplicated. </p>
  
  <p>I tried using the unique constraint (<code>Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity</code>). Tried </p>
  
  <pre><code> * @UniqueEntity("name")
   * @UniqueEntity("test")
  </code></pre>
  
  <p>and </p>
  
  <pre><code> * @UniqueEntity({"name", "test"})
  </code></pre>
  
  <p>Both seem to only trigger error when I have BOTH name and test duplicated. eg. </p>
  
  <ul>
  <li><p>obj1</p>
  
  <ul>
  <li>name: name1</li>
  <li>test: test</li>
  </ul></li>
  <li><p>obj2</p>
  
  <ul>
  <li>name: name2</li>
  <li>test: test</li>
  </ul></li>
  </ul>
  
  <p>Whats the right setup? Or I might have made a mistake somewhere?</p>
  
  <p>Perhaps I should include the doctrine annotation like: </p>
  
  <pre><code>@Table(name="ecommerce_products",uniqueConstraints={@UniqueConstraint(name="search_idx", columns={"name", "email"})})
  </code></pre>
  
  <p>But that still wont handle my symfony form validation I think?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>My test code:</p>
  
  <pre><code>/**
   * @ORM\Entity
   * @ORM\Table(name="roles") 
   * @UniqueEntity("name")
   * @UniqueEntity("test")
   */
  class Role {
  
      /**
       * @var integer
       * @ORM\Column(type="integer")
       * @ORM\Id
       * @ORM\GeneratedValue
       */
      protected $id;
  
      /**
       * @var string
       * 
       * @ORM\Column(type="string", length=32, unique=true)
       * @Assert\MaxLength(32)
       * @Assert\Regex("/^[a-zA-Z0-9_]+$/")
       */
      protected $name;
  
  }
  
  $v = $this-&gt;get('validator');
  
  $role = new Role();
  $role-&gt;setName('jm');
  $role-&gt;setTest('test');
  $e = $v-&gt;validate($role);
  echo '=== 1 ===';
  var_dump($e);
  if (count($e) == 0)
      $em-&gt;persist($role);            
  
  $role2 = new Role();
  $role2-&gt;setName('john');
  $role2-&gt;setTest('test');
  $e = $v-&gt;validate($role2);
  echo '=== 2 ===';
  var_dump($e);
  if (count($e) == 0)
      $em-&gt;persist($role2);
  
  $em-&gt;flush();
  </code></pre>
  
  <p>On first run (empty table): </p>
  
  <pre><code>=== 1 ===object(Symfony\Component\Validator\ConstraintViolationList)#322 (1) {
    ["violations":protected]=&gt;
    array(0) {
    }
  }
  === 2 ===object(Symfony\Component\Validator\ConstraintViolationList)#289 (1) {
    ["violations":protected]=&gt;
    array(0) {
    }
  }
  </code></pre>
  
  <p>But I do get an error on database layer about unique constraint. So how should I get Validation layer working tho? </p>