title: Symfony2 - how to recover from unique constraint error after form submission?
body: <p>I have an entity called <code>Contact</code> with a single unique field <code>email</code>. Also I have a form type used intended for an admin interface, let's call it <code>ContactType</code>. Everything described below happens using a form built with <code>ContactType</code>:</p>
  
  <p>Let's assume I want to add a contact with an email <code>mr.validated@example.com</code>, of course it works. Then I try again and bam, validation kicked in, error message says what happened. Perfect!</p>
  
  <p>Now I want to add another contact, this time with an email <code>mr.race.condition@example.com</code>, but oops, I accidentally submitted the form twice! Both requests are processed like this:</p>
  
  <pre><code> |    Request 1    |     Request 2
  -+-----------------+-----------------
  1|  $form-&gt;bind()  |   $form-&gt;bind()
  2|   Validation    |    Validation    
  3|   $em-&gt;flush()  |    $em-&gt;flush()
  </code></pre>
  
  <p>In both cases validation passed since the <code>Contact</code> entity with such email wasn't in database yet. This leads to two <code>Insert</code> queries with the same email. MySQL will prevent the second one, so Doctrine will throw an exception, user will see error 500 instead of "Email has been already taken".</p>
  
  <p>My question is: <strong>How do I make Symfony handle that for me?</strong> I just want to tell the user that he have to type in different email address.</p>
  
  <p>I could of course do something like this:</p>
  
  <pre><code>try {
      $this-&gt;getDoctrine()-&gt;getManager()-&gt;flush();
  } catch (DBALException $e) {
      $pdoException = $e-&gt;getPrevious();
      if ($pdoException &amp;&amp;
          $pdoException instanceof PDOException &amp;&amp;
          $pdoException-&gt;getCode() === '23000'
      ) {
  // let the form know about the error
      } else throw $e;
  }
  </code></pre>
  
  <p>But that's wrong, requires copy-pasting the code each time I have to deal with unique constraints, and is trouble in case there is more than one unique index.</p>