Is there an easy way to set a default value for text form field?
Often, for init default values of form i use fixtures. Of cause this way is not easiest, but very comfortable.
Example:
class LoadSurgeonPlanData implements FixtureInterface
{
public function load(ObjectManager $manager)
{
$surgeonPlan = new SurgeonPlan();
$surgeonPlan->setName('Free trial');
$surgeonPlan->setPrice(0);
$surgeonPlan->setDelayWorkHours(0);
$surgeonPlan->setSlug('free');
$manager->persist($surgeonPlan);
$manager->flush();
}
}
Yet, symfony type field have the option data.
Example
$builder->add('token', 'hidden', array(
'data' => 'abcdef',
));
If that field is bound to an entity (is a property of that entity) you can just set a default value for it.
An example:
public function getMyField() {
if (is_null($this->MyField)) {
$this->setMyField('my default value');
}
return $this->MyField;
}
As Brian asked:
empty_data appears to only set the field to 1 when it is submitted with no value. What about when you want the form to default to displaying 1 in the input when no value is present?
you can set the default value with empty_value
$builder->add('myField', 'number', ['empty_value' => 'Default value'])
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
if ($data == null) {
$form->add('position', IntegerType::class, array('data' => 0));
}
});
I solved this problem, by adding value in attr:
->add('projectDeliveringInDays', null, [
'attr' => [
'min'=>'1',
'value'=>'1'
]
])
If you need to set default value and your form relates to the entity, then you should use following approach:
// buildForm() method
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
...
->add(
'myField',
'text',
array(
'data' => isset($options['data']) ? $options['data']->getMyField() : 'my default value'
)
);
}
Otherwise, myField
always will be set to default value, instead of getting value from entity.