Is there an easy way to set a default value for text form field?
My solution:
$defaultvalue = $options['data']->getMyField();
$builder->add('myField', 'number', array(
'data' => !empty($defaultvalue) ? $options['data']->getMyField() : 0
)) ;
If your form is bound to an entity, just set the default value on the entity itself using the construct method:
public function __construct()
{
$this->field = 'default value';
}
Don't use:
'data' => 'Default value'
Read here: https://symfony.com/doc/current/reference/forms/types/form.html#data
"The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted."
Use the following:
Lets say, for this example, you have an Entity Foo, and there is a field "active" (in this example is CheckBoxType, but process is the same to every other type), which you want to be checked by default
In your FooFormType class add:
...
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
...
public function buildForm( FormBuilderInterface $builder, array $options )
{
...
$builder->add('active', CheckboxType::class, array(
'label' => 'Active',
));
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event){
$foo = $event->getData();
// Set Active to true (checked) if form is "create new" ($foo->active = null)
if(is_null($foo->getActive())) $foo->setActive(true);
}
);
}
public function configureOptions( OptionsResolver $resolver )
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle:Foo',
));
}
Approach 1 (from http://www.cranespud.com/blog/dead-simple-default-values-on-symfony2-forms/)
Simply set the default value in your entity, either in the variable declaration or the constructor:
class Entity {
private $color = '#0000FF';
...
}
or
class Entity {
private $color;
public function __construct(){
$this->color = '#0000FF';
...
}
...
}
Approach 2 from a comment in the above link, and also Dmitriy's answer (not the accepted one) from How to set default value for form field in Symfony2?
Add the default value to the data attribute when adding the field with the FormBuilder, adapted from Dmitriy's answer.
Note that this assumes that the property will and will only have the value null when it's a new, and not an existing, entity.
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('color', 'text', array(
'label' => 'Color:',
'data' => (isset($options['data']) && $options['data']->getColor() !== null) ? $options['data']->getColor() : '#0000FF'
)
);
}