Drupal - How do I pass parameters to the form builder?

The parameter has to have the same name in routing.yml and build method. And when using parameters in forms you have to set a null value in the parameter list:

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

First create a routing.yml file

admin_notes.form:
  path: '/example_module/form/{arg}'
  defaults:
    _form: '\Drupal\example_module\Form\ExampleForm'
  requirements:
    _permission: 'access content'

Then create a .php file under folder structure /src/Form/ExampleForm.php .Then build a form

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

             $form['example_note'] = array(
            '#type' => 'textarea',
            '#title' => t('Block contents'),
            '#description' => t('This text will appear in the example block.'),
            '#default_value' => $arg,
        );
       $form['actions'] = ['#type' => 'actions'];
        $form['actions']['delete'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Delete'),
        );

return $form;
}

Tags:

Forms

8