Rendering common form in drupal 8 and passing additional parameters

 

You may have scenario where in you need to pass extra parameter to form, using common/same forms in multiple places, You can do it just by passing params in buildform function in your form.

 

 create a .php file under folder structure /src/Form/Formname.php .Then build a drupal 8 form

With extra params in buildForm function

public function buildForm(array $form, FormStateInterface $form_state,$arg = NULL, $param2 = 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']['anything'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Delete'),
        );

return $form;
}

 

Calling function from your file

$form = \Drupal::formBuilder()->getForm('\Drupal\modulename\Form\Formname',$arg,$param2);