How to setup default form fields value from a form created in a controller?

I tryed to set the $form_state param but it does not work.

$form_state = new FormState();
$form_state->set('myfield_1', 'car');
$form_state->set('myfield_2', 'bus');
$form = $this->formBuilder->buildForm('Drupal\mymodule\Form\MyForm', $form_state);
return $form;

Add the default values to getForm():

return $this->formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $default1, $default2);

And set the default values in the form class:

class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, $default1 = NULL, $default2 = NULL) {

    $form['field1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Field 1'),
      '#default_value' => $default1,

    // ...


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.