Dynamically set the value of a form builder field
Created 1 year ago by squatto

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  —  1 year ago Best Answer

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 render() or make()

squatto  —  1 year ago

I was also able to do it like this, for existing fields:

public function index(YtdProductionFormBuilder $builder)
{
    $fields = $builder->getFields();
    $fields['from_date']['config']['default_value'] = now()->startOfYear();
    $fields['to_date']['config']['default_value'] = now();
    $builder->setFields($fields);

    return $builder->render();
}
ryanthompson  —  1 year ago

This feels.. like a setup! NO BADGES FOR YOU!