Override user registration form I'm looking for a OOP way to have a simplified User registration form in Drupal 8.

As of today, the default User registration form is declared directly as an annotation in the User class. From the administration pages, it is possible to add a Register form display for the user form. However, when removing all possible fields save for the password/login, there is still a bunch of fields showing up that I want removed:


Username
Password confirmation
Locales settings
Contact settings
etc.


What I want is an extremely simple registration form, with just two fields: e-mail address and password. All other fields will be editable later. I want this form to use OOP if possible, so extending the class Drupal\user\RegisterForm seems to me a good way to achieve this...

I extended the form but can't use it. It requires an entity to be passed to it apparently, but I don't know how to do that.

The ideal way to do it would be:

$entity = \Drupal::entityTypeManager()
  -&gt;getStorage('user')
  -&gt;create([])
;
$formObject = \Drupal::entityTypeManager()
  -&gt;getFormObject('user', 'register')
  -&gt;setEntity($entity)
;
$registerForm = \Drupal::formBuilder()-&gt;getForm($formObject);


However this will insist on fetching the original, non-inherited RegisterForm class, not my custom one. How can I tell Drupal to instanciate my own form instead?

BTW how can I make username optional?

I've seen a few solutions out there for redefining the user registration form, however most of them are Drupal 7 solutions and none of them are OOP.
If you want to use the extended register form class, you need to put it in the place of the original form class in the user entity type:

mymodule.module

  /**
   * Implements hook_entity_type_alter().
   */
  function mymodule_entity_type_alter(array &amp;$entity_types) {
    $entity_types['user']-&gt;setFormClass('register', 'Drupal\mymodule\MyRegisterForm');
  }