Dynamically set the value of a form builder field
squatto - 6 months ago
Is it possible to set the value of a form field dynamically? e.g. in the controller. I've tried all of these, and none work:
$request->merge(['from_date' => now()]); $builder->setFormValue('from_date', now()); $builder->getForm()->setValue('from_date', now()); $builder->getForm()->setFieldValue('from_date', now()); $builder->getForm()->getField('from_date')->setValue(now());
edster - 6 months ago
Yea I had the same issues haha.
You want to use the
default_value for the field configs.
$fields = $builder->getFields(); $fields = array_merge($fields, [ 'pid' => [ 'required' => TRUE, 'config' => [ 'default_value' => 'My Dynamic Default Value' ] ] ]); $builder->setFields($fields);
Few things to note, if you are trying to set a field you already declared in your builder, you want to make sure your fields in your builder are arrays, otherwise if you try to merge them, they duplicate.
You also want to make sure you do this before you