In Drupal 8, if I want to create a form, I have to define a class inside the module folder like this.

class MyForm extends FormBase{

   public function getFormId()
     return 'my_form';
   public function buildForm(array $form, FormStateInterface $form_state)


Then I need to register a path for it in module.routing.yml.

  path: '/admin/structure/myform'
    _form: '\Drupal\my_formr\Form\MyForm'
    _title: 'My form'
    _permission: 'administer banner configuration'

Where is the MyForm class instantiated? What calls all the methods we are overriding?

We just define the class and register a path for it; neither we create an object of that class, nor we invoke any of the methods.

So, how does Drupal 8 manage these classes?

1 Answer 1


So, first, this is not a controller, it's a form class. Controllers are instantiated by the routing component.

Every route must have a controller. _form and some other special cases are processed after routes were collected and the actual controller is added. For forms, that is \Drupal\Core\Controller\HtmlFormController.

The actual processing happens in \Drupal\Core\Controller\FormController::getContentResult(), which calls \Drupal\Core\Controller\HtmlFormController::getFormObject(), which in turn uses \Drupal\Core\DependencyInjection\ClassResolverInterface::getInstanceFromDefinition() to instantiate the form class.

FormController then hands of the processing of the form to \Drupal\Core\Form\FormBuilder, which uses various other classes in the Form namespace.


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.