title: Entity mapping in a Symfony2 choice field with optgroup
body: <p>Suppose to have an entity in <strong>Symfony2</strong> that has a field <code>bestfriend</code>, which is a <code>User</code> entity selected from a list of <code>User</code> entities that satisfy a complex requirement. 
  You can render this field in a form by specifying that it is an <a href="http://symfony.com/doc/current/reference/forms/types/entity.html#basic-usage" rel="nofollow noreferrer">entity field type</a>, i.e.:</p>
  
  <pre><code>$builder-&gt;add('bestfriend', 'entity', array(
     'class' =&gt; 'AcmeHelloBundle:User',
     'property' =&gt; 'username',
  ));
  </code></pre>
  
  <p>This form field is rendered as a  <code>&lt;select&gt;</code>, where each one of the displayed values is in the form:</p>
  
  <pre><code>&lt;option value="user_id"&gt;user_username&lt;/option&gt;
  </code></pre>
  
  <p>So, one would render the field by using the <code>&lt;optgroup&gt;</code> tags to highlight such special feature of the friends. </p>
  
  <p>Following this principle, I created a field type, namely <code>FriendType</code>, that creates the array of choices as in <a href="https://stackoverflow.com/questions/12244376/select-with-optgroup-in-symfony-2-0">this answer</a>, which is rendered as follows:</p>
  
  <pre><code>$builder-&gt;add('bestfriend', new FriendType(...));
  </code></pre>
  
  <p>The <code>FriendType</code> class creates a <code>&lt;select&gt;</code> organized with the same <code>&lt;option&gt;</code>s but organized under <code>&lt;optgroup&gt;</code>s.</p>
  
  <p>Here I come to the problem! When submitting the form, the framework recognize that the user field is not an instance of User, but it is an integer. <strong>How can I let Symfony2 understand that the passed int is the id of an entity of type User?</strong></p>