title: Set default values using form classes in Symfony 2
body: <p>I am trying to define a default value for a text field in Symfony 2.3. The form is used both for creating and updating the entity. In edit mode the value given by the database should be used, not the default (of course). </p>
  
  <p><strong>Edit</strong>
  This seems to be a common problem, lots of people viewed this post <a href="https://stackoverflow.com/questions/7913086/how-to-set-default-value-for-form-field-in-symfony2">How to set default value for form field in Symfony2?</a></p>
  
  <p>Yet the answers are not satisfying (for me):</p>
  
  <ul>
  <li>using the data attribute is "wrong", it will always be used, not only when the form element has no value</li>
  <li>using the data attribute using the if - then - else approach works (while the syntax in the answer is wrong). I doubt that this is the way it should be done in Symfony.</li>
  <li>another suggestion is to set default values in the model like "protected $foo = 'myValue'". This works for some field types (e.g. text fields) but not all.</li>
  <li>using EventListeners might work, but it's so much work that it can't be the intended way for this basic task</li>
  <li>setting it in the twig template does not work if you work with the form_widget tag and you have to set it multiple times if you use the form in different templates</li>
  </ul>
  
  <p>So I am still looking for the "perfect" way, i.e. the way the Symfony developers provided (there must be one, this is such a basic requirement). </p>
  
  <p>This is what I have so far, yet it does not work (no default is shown in the form).
  Is this the right approach at all?</p>
  
  <pre><code>// Acme\DemoBundle\Form\ProjectType.php
  class ProjectType extends AbstractType
  {
  
      public function __construct(array $options = array())
      {
          $resolver = new OptionsResolver();
          $this-&gt;setDefaultOptions($resolver);
          $this-&gt;options = $resolver-&gt;resolve($options);
      }
  
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder-&gt;add('color', 'text', array(
                  "label" =&gt; "Color:"
              )
          );
      }
  
      public function setDefaultOptions(OptionsResolverInterface $resolver)
      {
          $resolver-&gt;setDefaults(array(
              "color" =&gt; "#0000FF"
          ));
      }
  }
  </code></pre>