Rendering forms

Staying on forms for just a bit longer, let's quickly learn how to render forms programmatically. Also, we have already seen how to map a form to a route definition so that the page being built contains the form when accessing the route path. However, there are times where we need to render a form programmatically, either inside a Controller or a block or wherever you want. We can do this using the FormBuilder service.

The form builder can be injected using the form_builder service key or used statically via the shorthand:

$builder = \Drupal::formBuilder();

Once we have it, we can build a form, like so:

$form = $builder->getForm('Drupal\hello_world\Form\SalutationConfigurationForm');

In the preceding code, $form will be a ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.