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;

2 Answers 2


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,

    // ...


The working example for add node form:


        namespace Drupal\mymodule\Controller;

        use Drupal\Core\Controller\ControllerBase;

        class addController extends ControllerBase {

           public function build() {

             $entity = $this->entityTypeManager()->getStorage('node')->create(array(
               'type' => 'SomeContentType',

             $entity->set('field_link_to_item', 5);

             $form = $this->entityFormBuilder()->getForm($entity);

             return $form;


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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