How can I programmatically extend the registration form? I'm trying to extend registration form programatically to add an additional field. I was following an example from Extend _form in Drupal 8

I created a new service that will redirect to the new form.
I created a route subscriber to that will return the new form.
I created a form class that will extend the form.

It works for the user login form but wont work on user registration form because it is an _entity_form and I guess it should be treated differently. I changed the router subscriber to match registration form but i get this error.

Call to a member function getEntityTypeId() on null.
if ($route = $collection-&gt;get('user.register')) {$route-&gt;setDefault('_entity_form',
'\Drupal\form_overwrite\Form\NewUserLoginForm');

Can anyone suggest please what's the right way to extend this form?
I tried with the all known hook_form_alter but even like that I'm not sure how to save the new field content in the configuration files.
I had this same question and it doesn't seem to be answered anywhere so I'll give the answer that I figure out, hopefully this helps someone.
First you need to add the form to the entity do this in the module file in hook_entity_type_build something like the following sample:
/**
 * Implements hook_entity_build
 */
function MYMODULE_entity_type_build(array &amp;$entity_types) {

  $entity_types['user']-&gt;setFormClass(
    'MYMODULE_register',
    'Drupal\MYMODULE\Form\myModuleRegisterForm'
  );
}

Create a new class src/Form/myModuleRegisterForm.php to extend RegisterForm:
namespace Drupal\MYMODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RegisterForm;

class myModuleRegisterForm extends RegisterForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
        
    $form = parent::form($form, $form_state);

    // Change the form here

    return $form;
  }

}

Then load it in your controller
public function myModuleRegister {

  $build = [];

  $entity = \Drupal::entityTypeManager()
    -&gt;getStorage('user')
    -&gt;create([]);

  $formObject = \Drupal::entityTypeManager()
    -&gt;getFormObject('user', 'MYMODULE_register')
    -&gt;setEntity($entity);

   $build['form'] = \Drupal::formBuilder()-&gt;getForm($formObject);

   return $build;
}

That pretty much covers it, obviously you need the route to point to the appropriate function in your controller but otherwise this should do it.  Hope it helps.