Skip to content

Instantly share code, notes, and snippets.

@davidDuymelinck
Last active June 1, 2017 07:52
Show Gist options
  • Save davidDuymelinck/cd20ab7049749358717127f12666b68c to your computer and use it in GitHub Desktop.
Save davidDuymelinck/cd20ab7049749358717127f12666b68c to your computer and use it in GitHub Desktop.
Extend drupal 8 user register form
<?php
namespace Drupal\my_module\Form;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\user\Entity\User;
use Drupal\user\RegisterForm;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a user login form.
*/
class NewUserRegisterForm extends RegisterForm {
public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, ModuleHandlerInterface $moduleHandler) {
$this->setEntity(new User([], 'user'));
$this->setModuleHandler($moduleHandler);
parent::__construct($entity_manager, $language_manager, $entity_type_bundle_info, $time);
}
/**
* @inheritdoc
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager'),
$container->get('language_manager'),
$container->get('entity_type.bundle.info'),
$container->get('datetime.time'),
$container->get('module_handler')
);
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['test'] = [
'#markup' => '<p>Test extended form</p>',
];
return $form;
}
}
<?php
namespace Drupal\my_module\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('user.register')) {
$route->setDefault('_form', '\Drupal\my_module\Form\NewUserRegisterForm');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment