How to render user login form and user register form in Drupal 8

Posted by admin on Thu, 06/29/2017 - 10:04

I've spend an hour to understand how to render user login form and user register form in Drupal 8 to print them in a custom place.
Here is the solution.

Lets say you want to print those two forms in a custom place on your page (in a popup in my case).

So if you want to print it in the page.html.twig - so in the THEMENAME.theme write this first:

function THEMENAME_preprocess_page(&$variables) {

User login form

$form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
$render = Drupal::service('renderer');
$variables['login_form'] = $render->renderPlain($form);

User registration form

    $entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());
    $formObject = \Drupal::entityTypeManager()
      ->getFormObject('user', 'register')
    $form = \Drupal::formBuilder()->getForm($formObject);
    $variables['register_form'] = \Drupal::service('renderer')->render($form);

The final step would be to output the results using your twig template.
For example in page.html.twig you just write to ouput the login form:

{{ login_form }}

Or register form:

{{ register_form }}

Hey! Don't miss a new cool stuff!


summer (not verified)

Thanks! I'm sure you saved me a ton of time and one less module!

sudharson (not verified)

Thanks, it saves me lot of time

Julius (not verified)

Thanks, works good on pages. If I try to use it on nodes it produces an error. Do I have to change anything if I have THEMENAME_preprocess_node ?


What error do you have, could you explain?

Navneet (not verified)

Thanks! You saved my lots of time

johnatasjmo (not verified)

Can you share the full code in a git repo? Thks

Nhat (not verified)

Can you share the full code .. Thanks


The full code is in the article ;)
So you need to add inside you THEMENAME.theme:

function THEMENAME_preprocess_page(&$variables) {
  $form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
  $render = Drupal::service('renderer');
  $variables['login_form'] = $render->renderPlain($form);

Then inside your page.html.twig:
Just add {{ login_form }} to print login form wherever you want.

Alex (not verified)

working in page.html.tpl but not work if i use for example menu.html.tpl :(

Lalit (not verified)

How to render the password reset form in another file like login and register form

Alvaro (not verified)

Very useful info but do you know how get it working in block--myblock.html.twig template instead page.html.twig?

Thank a ton in advance.

Catherine (not verified)

oh my goodness thank you so much!

aftab ali (not verified)

Here while influencing a determination you to must be watchful about the subtleties and need to confirm all.

Sebastian (not verified)

Thank you very much, this helped me a ton!

Add new comment