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).
Edit This seems to be a common problem, lots of people viewed this post How to set default value for form field in Symfony2?
Yet the answers are not satisfying (for me):
- using the data attribute is "wrong", it will always be used, not only when the form element has no value
- 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.
- 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.
- using EventListeners might work, but it's so much work that it can't be the intended way for this basic task
- 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
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).
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?
// Acme\DemoBundle\Form\ProjectType.php
class ProjectType extends AbstractType
{
public function __construct(array $options = array())
{
$resolver = new OptionsResolver();
$this->setDefaultOptions($resolver);
$this->options = $resolver->resolve($options);
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('color', 'text', array(
"label" => "Color:"
)
);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
"color" => "#0000FF"
));
}
}